读书人

const摘引会延长临时变量的寿命与自己

发布时间: 2013-08-10 21:14:06 作者: rapoo

const引用会延长临时变量的寿命与自己一样?
如果一个函数返回一个临时变量,const引用绑定这个临时变量,那么它会延长这个临时变量的寿命与自己一样?
[解决办法]

引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

Quote: 引用:

取决于实现,没有强制要求。 VC好像会延长生命。
标准有明确规定声明周期要延长到和引用的一样
5 The second context is when a reference is bound to a temporary. The temporary to which the reference is
bound or the temporary that is the complete object of a subobject to which the reference is bound persists
for the lifetime of the reference except:
— 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 a reference parameter in a function call (5.2.2) persists until the completion of
the full-expression containing the call.
— The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not
extended; the temporary is destroyed at the end of the full-expression in the return statement.
— A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the
full-expression containing the new-initializer.

没看到标准严格规定必须是const引用,怎么G++要求必须是const引用才能绑定临时变量。
这段是在讲临时变量的生命周期,不是在讲引用
讲引用的地方有

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
— If the reference is an lvalue reference and the initializer expression
(略)
— Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be


const), or the reference shall be an rvalue reference.


用const引用来引用临时变量,是标准提倡的,还是标准规定必须这么做的?
必须的

读书人网 >C++

热点推荐