O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Return Value Optimization

Without any optimization, the compiler-generated (pseudo) code for Complex_Add() is

void Complex_Add(const Complex& __tempResult,
              const Complex& c1,
              const Complex& c2)
{
    struct Complex retVal;
    retVal.Complex::Complex();                    // Construct retVal

    retVal.real = a.real + b.real;
    retVal.imag = a.imag + b.imag;

    __tempResult.Complex::Complex(retVal);// Copy-construct
                                                  // __tempResult
    retVal.Complex::~Complex();                   // Destroy retVal
    return;
}

The compiler can optimize Complex_Add() by eliminating the local object retVal and replacing it with __tempResult. This is the Return Value Optimization:

 void Complex_Add (const Complex& __tempResult, const Complex& c1, const Complex& c2) { __tempResult.Complex::Complex(); // Construct __tempResult ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required