右值参考的生命周期 [英] Lifetime of rvalue reference

查看:174
本文介绍了右值参考的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于右值参考的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆