hjk41的日志

Avatar

More Effective C++ 22: Consider using op= instead of stand-alone op

The operator += is usually more efficient than + because operator + always returns a new object while += doesn't.
For efficiency, we should provide the operator += and implement operator + in terms of +=.


class Rational {
public:
  ...
  Rational& operator+=(const Rational& rhs);
  Rational& operator-=(const Rational& rhs);
};

const Rational operator+(const Rational& lhs,
                         const Rational& rhs)
{
  return Rational(lhs) += rhs;
}

const Rational operator-(const Rational& lhs,
                         const Rational& rhs)
{
  return Rational(lhs) -= rhs;
}


And we can use templates to simplify this:


template<class T>
const T operator+(const T& lhs, const T& rhs)
{
  return T(lhs) += rhs;                     // see discussion below
}

template<class T>
const T operator-(const T& lhs, const T& rhs)
{
  return T(lhs) -= rhs;                      // see discussion below
}


As you can see, the return value is T(lhs) -= rhs. This is an unnamed object, which makes return value optimization possible.

评论已关闭