1

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?

athos
  • 6,120
  • 5
  • 51
  • 95
  • note, the standard term for RVO and NRVO is [copy elision](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – M.M Dec 31 '14 at 07:47
  • @MattMcNabb yes i can see it now. thanks! – athos Dec 31 '14 at 07:48

1 Answers1

5

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.

4pie0
  • 29,204
  • 9
  • 82
  • 118