右值参考的生命周期

问题描述:

我认为我在理解右值引用时遇到问题。这种构造的寿命和用途到底是什么。

I think I have a problem with understanding rvalue references. What is really the lifetime and usage of such construction.

int&& value = 5;

如果我理解正确,5是右值对象(我无法获取它的地址),它是临时-生存期是当前表达式的结尾。将其分配给右值引用是否可以延长寿命?如果是,对象的新生命周期是什么?

If I understand correctly, 5 is rvalue object (I can't take address of it) and it's temporary - lifetime is end of current expression. Does assigning that to rvalue reference somehow prolong lifetime? If yes, what is the new lifetime of object?


是否以某种方式将其分配给右值引用延长寿命?

Does assigning that to rvalue reference somehow prolong lifetime?

是。 右值引用可用于延长临时对象的寿命(请注意, const 的c $ c> lvalue引用也可以延长临时对象的寿命,但不能通过它们进行修改。因此:

Yes. Rvalue references can be used to extend the lifetimes of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them). Thus:

// both will extend the lifetime of the temporary
int&& value = 5;      // modifiable
const int& value = 5; // non-modifiable




如果是,新生命周期是多少目的?

If yes, what is the new lifetime of object?

扩展了临时项的生存期以匹配引用的生存期。请参见临时工的寿命。

The lifetime of the temporary is extended to match the lifetime of the reference. See lifetime of a temporary.