11

I'm learning new C++ 11 features recently. However, I don't fully understand one thing about rvalues.

Consider following code:

string getText ()
{
    return "Fabricati diem";
}

string newText = getText();

Call to getText() creates an r-value which is copied to newText variable. But where exactly is this rvalue stored? And what happens to it after copying?

Kao
  • 7,225
  • 9
  • 41
  • 65
  • 1
    Actually it is not copied due to [return value optimization](http://en.wikipedia.org/wiki/Return_value_optimization) – Cory Kramer Jan 08 '15 at 13:44
  • 7
    @Cyber It can't be moved *and* RVO'd. It is one or the other, most likely the latter. – juanchopanza Jan 08 '15 at 13:45
  • 1
    isn't stack the answer? – ha9u63a7 Jan 08 '15 at 13:54
  • 3
    Expressions can be (have to be either) rvalue or lvalue expressions. Values themselves are not rvalue or lvalue. Yes, it's a bit misleading terminology. – Cheers and hth. - Alf Jan 08 '15 at 13:55
  • The answer depends on the compilation target. The standard doesn't specify that. If that function wasn't RVO-able, the string would probably be stored somewhere in .rdata/.rodata (so, technically on the heap). – tux3 Jan 08 '15 at 14:01

1 Answers1

13

Call to getText() creates an r-value which is copied to newText variable.

It might create a temporary; but this is one situation in which copy elision is allowed, so it's more likely that newText is initialised directly by the function return, with no temporary.

But where exactly is this rvalue stored?

It's up to the compiler where to store a temporary; the standard only specifies its lifetime. Typically, it will be treated like an automatic variable, stored in registers or in the function's stack frame.

And what happens to it after copying?

The lifetime of a temporary extends to the end of the full-expression which created it (unless it's used to initialise a referenece, in which case it lasts as long as that reference). So here, it's destroyed immediately after using it to initialise newText.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644