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 ...

Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.