C++ const 左值引用
假设我有:
- A 类是不可复制的
- B 类,其成员为 const A& a(并在其构造函数中采用 A 并将其设置在其初始化列表中)
- 函数
AGenerateA();
这是否意味着它应该有效执行: B(生成A()) ?
即,const ref 是否意味着generateA() 返回的A 的副本尚未完成?这是否意味着只要 B 存在,返回的临时值的范围就会扩展?
编辑:评论中的附加问题: 返回 A& 是否可以接受?从GenerateA()到本地A,如果左值是const A&?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
A
是不可复制的,则函数AGenerateA()
无效,因为按值返回需要创建副本。如果函数返回一个引用(即
A &GenerateA()
),并且该引用指向本地创建的A
对象,则一旦函数退出,该引用就会失效。 C++ 没有任何形式的垃圾收集,因此只要对象正在使用,就没有办法“延长”它的生命周期。If
A
is non-copyable, then the functionA GenerateA()
is invalid since returning by value requires creating a copy.If the function returns a reference instead (i.e.
A &GenerateA()
) and the reference is to a locally createdA
object, it becomes invalid as soon as the function exits. C++ doesn't have any form of garbage collection, so there is no way to "extend" the lifetime of an object as long as it is in use.正如其他人已经指出的那样,如果
A
不可复制,则AGenerateA()
无法编译。关于 const ref :不,临时的生命周期不会延长到 B 的生命周期。标准 [12.2.5] 规定:
所以,是的,在某些情况下存在临时生命周期的延长(有时确实有用:请参阅这篇文章),但不在您介绍的文章中。
关于您的最后一个问题,从
GenerateA()
返回对局部变量的引用是不合法的(并且将结果绑定到 const 引用不会有任何帮助)。As it has already been stated by others,
A GenerateA()
cannot compile ifA
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 :
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).是和否。
是的,const 引用将绑定到临时变量。不,作为类成员的 const 引用不会像具有自动持续时间的 const 引用那样延长生命周期。
Yes and No.
Yes, the const reference will bind to the temporary variable. No, const references which are class members do not extend lifetime the way const references with automatic duration do.
这是一个示例:
输出:
Here's an example:
Output: