Return Value Optimization(RVO)

Let us try to understand RVO(Return value optimization) with the help of below example:

#include <iostream>
using namespace std;
class base
{
    unsigned int m_mem1;
    unsigned int m_mem2;
public:
    base(unsigned int x, unsigned int y): m_mem1(x), m_mem2(y)
    {
         cout << “base C’tor” << endl;
    }
    ~base()
    {
         cout << “base d’tor” << endl;
    }
    base(const base& b)
    {
        m_mem1 = b. m_mem1;
        m_mem2 = b. m_mem2;
        cout << “Copy C’tor” << endl;
    }

    static base getNewInstance()
    {
        base b(10,20);
        return b;
    }
};

int main()
{
    base b = base::getNewInstance();
    return 0;
}

Output:

base C’tor
Copy C’tor
base d’tor
base d’tor

In the getNewInstance function, three thing happens

  • A new object is created including constructor of base class.
  • Copy constructor is called because object is returned by value.
  • Finally destructor is called for the object created inside the function.

If the intention is to return a new object from function i.e. to avoid last two steps (copy constructor and destructor) and only constructor should be called while calling getNewInstance, getNewInstance can be written in the below manner.

static base getNewInstance()
{
return base(10,20);
}

If this function is used then output will be:
base C’tor
base d’tor

In the above function, compiler see that it just return new object, then it construct an object directly in to the location which is outside the function. This way only constructor is called since no local object is created.

For RVO to be effective, object should be created on return statement as shown in the above example.

Related posts