我可以使用rvalue引用临时吗?它是未定义的行为还是不行? [英] Can I use rvalue reference to temporary? Is it undefined behavior or not?

查看:178
本文介绍了我可以使用rvalue引用临时吗?它是未定义的行为还是不行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新问题为什么这两个右值引用示例具有不同的行为?

源代码:

int a = 0;
auto && b = a++;
++a;
cout << a << b << endl;

列印 20

a ++ 调用之后使用 b 是未定义的行为也许我们不能使用 b ,因为它指的是临时的

Is it undefined behavior (UB) to use b after the a++ call? Maybe we cannot use b because it refers to a temporary?

推荐答案

不是没有未定义的行为(UB)。很好 - 你可以在这里修改临时内容(只要引用对临时的生命周期是有效的,在这种情况下绑定到右值引用将右值的生存期延长到引用的生命周期)。

No it is not undefined behavior (UB). It's fine - you can modify the contents of the temporary here (so long as the reference is valid for the lifetime of the temporary, in this case the bind to the rvalue reference extends that lifetime of the rvalue to the lifetime of the reference).

更常见的问题是:是UB修改临时通过右值引用?不是不是UB。移动语义,其中移动到对象窃取移动对象的内容,依赖于这是被明确定义的。

A more general question is; is it UB to modify a temporary through the rvalue reference? No it is not UB. Move semantics, where the "moved-to" object "steals" the "moved-from" object's contents, relies on this to be well defined.

这篇关于我可以使用rvalue引用临时吗?它是未定义的行为还是不行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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