简体   繁体   English

rvalues在C ++中存储在哪里?

[英]Where are rvalues stored in C++?

I'm learning new C++ 11 features recently. 我最近正在学习新的C ++ 11功能。 However, I don't fully understand one thing about rvalues. 但是,我并不完全了解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. 调用getText()会创建一个复制到newText变量的r值。 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. 调用getText()会创建一个复制到newText变量的r值。

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. 但这是允许复制省略的一种情况,因此更有可能newText由函数return直接初始化,没有临时值。

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 . 所以在这里,它在使用它初始化newText后立即被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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