Search code examples
c++compiler-constructionreturn-value-optimization

How does the compiler determine when is it safe to RVO?


How does the compiler determine when it is safe to RVO? And no, I don't mean the rvalue, but the lvalue - if I understand correctly RVO works by "forwarding" the target address to the method, so it returns into the target address instead of the address of a temporary and then copy/assign to the target.

But how does the compiler know it is safe to perform a RVO? What if the lvalue already has some data in it, including dynamically allocated resource? A RVO in such a case may result in a leaked resource. Mayhaps there are some rules which specify whether it is applicable to perform the optimization or stick to using copy or assignment?


Solution

  • RVO can only initialise a new object, not reassign an existing object. So in this case:

    Thing thing = make_thing();
    

    the address of thing is passed to the function, which initialises it in place.

    In this case:

    thing = make_thing();
    

    RVO (in general) creates a temporary, which is then assigned to thing. There will be no leaks or similar issues, as long as the type is correctly assignable. Since it's a temporary rvalue, it can be moved from, which might be more efficient than copying. If the type is trivially assignable, then this assignment could also be elided - the compiler will know whether this is the case when it chooses how to call the function.