Search code examples
c++rvonrvo

C++: RVO, NRVO and returning local objects


I just read about RVO (Return Value Optimization) and NRVO (Named Return Value Optimization). Below are two examples

//Example of RVO
Bar Foo()
{
    return Bar();
}

//Example of NVRO
Bar Foo()
{
    Bar bar;
    return bar;
}

That makes sense, a nice compiler optimization. However, I read from Stanley Lippman's "C++ primer" that "Never return a Reference or Pointer to a Local Object" (ch 6.3.2), the example code is

//disaster: this function returns a reference to a local object
const string &manip()
{
    string ret;
    // transform ret in some way
    if (!ret.empty())
        return ret;  // WRONG: returning a reference to a local object!
    else
        return "Empty"; // WRONG: "Empty" is a local temporary string
}

I don't get it, is this example anywhere different from the RVO example? If they are the same, how could I ensure the compiler will do RVO optimization, instead of causing undefined behavior due to the call stack unwinding?


Solution

  • They are different.

    Bar Foo();
    

    returns by value, the local object is copied.

    const string &manip();
    

    returns by reference, a local object itself is returned, and reference is invalid in the same time the function returns.