简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM