Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are rvalues stored in C++?

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?

like image 492
Kao Avatar asked Jan 08 '15 13:01

Kao


1 Answers

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.

like image 131
Mike Seymour Avatar answered Sep 21 '22 13:09

Mike Seymour