C ++:常量引用临时
关于SO上持续引用的生存期有几个问题,但我仍然不明白.
There are several questions about lifetime of constant reference on SO, but still I don't get it.
这段代码有效吗?
struct S
{
const int &ref;
S( const int &x ) : ref(x) { }
};
int main( )
{
S s( 0 );
// ...
use( s.ref );
// ...
return 0;
}
直觉上我不会,因为0
应该在表达式(S s(0);
)求值后过期.
Intuitively I'd say no, since 0
should expire after the expression (S s(0);
) is evaluated.
但是GCC和CLANG都可以很好地编译它,而不会发出警告,并且valgrind不会检测到任何运行时错误.
However both GCC and CLANG compile it fine, without warnings, and valgrind doesn't detect any runtime error.
我对参考文献缺少什么?
What am I missing about references?
根据12.2/4,对我来说似乎无效:
Seems invalid to me according to 12.2/4 :
在两种情况下 临时人员在 与终点不同的地方 全表达.第一个上下文是 当表达式显示为 声明程序定义的初始值设定项 一个对象. 在这种情况下, 临时保存的结果 表达应一直持续到 对象的初始化已完成.
There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object’s initialization is complete.
临时对象只有在完全构建s
之前才能生存,直到调用use
的那一点都没有.
The temporary only gets to live until s
is fully constructed, not until the point where use
is called.