menu

hjk41的日志

Avatar

More Effective C++ 20: Facilitate the return value optimization

Returning objects by value is always costy, but you can minimize the cost using return value optimization.


class Rational {
public:
  Rational(int numerator = 0, int denominator = 1);
  ...
  int numerator() const;
  int denominator() const;
};

// without return value optimization
const Rational operator*(const Rational& lhs,
                          const Rational& rhs)
{
  Rational result(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
  return result;
}

// with return value optimization
const Rational operator*(const Rational& lhs,
                         const Rational& rhs)
{
  return Rational(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
}

Rational c=a*b;


Though these two implementations of operator * look much the same, the second implementation enables the compiler to optimize. By writing return value like this, you are telling the compiler that it can eliminate the temporary object that otherwise would be created. Thus with the second impementation, the compiler actually replaces c=a*b with:


Rational c(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());


And that's just what we want: no construction or destruction of temporary objects.

评论已关闭