C ++:常量引用临时 [英] C++: constant reference to temporary

查看:90
本文介绍了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.

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

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