//单独形式
x = x + y; x = x - y;
//也可以写为复合形式
x += y; x -= y;
效率问题
- 一般而言,复合操作符比其对应的单独形式效率高:因为单独形式需要返回一个新的对象,就会产生一个临时对象的构造和析构成本,复合版本则是直接写入左端自变量,不需要产生一个临时对象来放置返回值。
- 同时提供复合和单独形式,允许客户端在便利和效率之间抉择;
- 单独形式调用T的复制构造函数,它建立了临时对象与rhs一起调用+=,运算结果从operator+返回。这样会比使用命名对象效率更高,因为使用了返回值最优化的方法(RVO)。
//operator+根据operator+=来实现
const Rational operator+(const Rational& lhs,const Rational& rhs)
{return Rational(lhs) += rhs;
}
//operator-根据operator-=来实现
const Rational operator-(const Rational& lhs,const Rational& rhs)
{return Rational(lhs) -= rhs;
}template<typename T>
const T operator + (const T& lhs,const T& rhs)
{return T(lhs) += rhs;
}template<typename T>
const T operator +(const T& lhs,const T& rhs)
{return T(lhs) += rhs;//相比于//T result(lhs);//return T(lhs) += rhs;
}
综上
operator的复合形式(operator+=)比单独形式(operator+)效率更加高,开发时优先考虑使用复合形式。