Search code examples
c++return-valuervalue-reference

return value optimization vs rvalue reference


I learned about return value optimization (Object return in C++, http://en.wikipedia.org/wiki/Return_value_optimization, http://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/) that prevents temporary object generation.

I also learned about rvalue reference (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html) that also can be used to prevent temporary object generation.

Practically, can I just return value not worrying about performance degradation from copying objects?

I mean, are those two code snippet equivalent?

A hello()
{
    A a(20);
    cout << &a << endl;
    return a;
}

// rvalue reference to prevent temporary object creation
A&& a = hello();
cout << &a << endl;

// expects compiler remove the temporary object
A a = hello();
cout << &a << endl;

Solution

  • First and foremost you should return by value if you logically want to give the caller a new object. If RVO can't occur then a move will happen. If I move can't happen, a copy will happen. Move's are often trivial, but it depends on the object obviously. If you are returning a non-movable type which is expensive to copy, it becomes a more difficult decision of whether you can rely on RVO. Luckily, that should be a rare case.

    RVO is so widely applicable that it's fairly difficult to make it not happen. I know on some compilers a ternary statement for the return value will break it though. In VS at least, NRVO won't happen in debug. So, it's worth noting debug build performance will be affected.

    Look at the assembly your compiler generated for your particular code above to see if it's the same for both cases. It most likely is.