C ++常量值引用 [英] C++ const lvalue references

查看:217
本文介绍了C ++常量值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:




  • 不可复制的A类

  • B类作为成员,const A& a

  • 一个函数 A GenerateA();



这是否意味着它应该是有效的:
B(GenerateA())



即,const ref是否意味着generateA()返回的A的副本没有被复制?这是否意味着只要B存在,返回的临时的范围就扩展了?



编辑:添加问题的意见:
是可接受的返回A&感谢!



< >解决方案

由于其他人已经说过, A GenerateA()无法编译 A 不可复制。



关于const ref:no,临时的生存期不会延长到B的生存期。标准[12.2.5 ] states:


在构造函数的ctor-initializer(12.6.2)中临时绑定到引用成员,直到构造函数退出。 [...]函数返回语句(6.6.3)中返回值的临时绑定将一直存在,直到函数退出。


所以是的,一个临时的生命周期的延长存在于某些上下文中(有时真正有用:请参阅这篇文章),但不在您提供的一个。



最后一个问题,从 GenerateA()(并将结果绑定到一个const引用不会有任何帮助)返回一个局部变量的引用是不合法的。 / p>

Assuming I have:

  • class A which is non-copyable
  • class B which has as a member, const A& a (and takes an A in its constructer and sets it in its initialization list)
  • a function A GenerateA();

Does this mean that it should be valid to do: B(GenerateA()) ?

i.e, does the const ref mean that no copy of the A that generateA() returns is done? And does that mean that the scope of the returned temporary is extended for as long as B exists?

EDIT: Addon question from the comments: Is it acceptable to return a A& from GenerateA() to a local A, if the lvalue is a const A&?

Thanks!

解决方案

As it has already been stated by others, A GenerateA() cannot compile if A is not copyable.

Regarding the const ref : no, the lifetime of the temporary will not be extended to the lifetime of B. The standard [12.2.5] states :

A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits. [...] A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits.

So yes, extension of the lifetime of a temporary exists in some contexts (and is sometime truly useful : see this article), but not in the one you presented.

Regarding your last question, it's not legal to return a reference to a local variable from GenerateA() (and binding the result to a const reference won't be of any help).

这篇关于C ++常量值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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