C ++常量值引用

编程入门 行业动态 更新时间:2024-10-28 22:23:41
本文介绍了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 ++常量值引用

本文发布于:2023-11-12 18:08:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:量值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!