const引用数据成员,该成员绑定到构造函数中的该引用的临时初始化 [英] const reference data member bound to a temporary initializing that reference in a constructor

查看:65
本文介绍了const引用数据成员,该成员绑定到构造函数中的该引用的临时初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <iostream>

struct A {
    const char *name;

    A() : name("A") {
        std::cout << "A()\n";
    }

    virtual ~A() {
        std::cout << "~A()\n";
    }
};

class B {
    const A& a;
public:

    B() : a(A()) {
    };

    void print_data() const {
        std::cout << a.name << '\n';
    }

    ~B() {
        std::cout << "~B()\n";
    }
};

int main() {
    B b;
    b.print_data();
    return 0;
}

GCC 4.4的输出是:

The output from GCC 4.4 is:

A()〜A()A〜B()

A() ~A() A ~B()

这对我来说很奇怪.我本来希望要么将A的临时实例的副本绑定到B :: a,要么在〜B()期间销毁该临时实例.

This looks strange to me. I would have expected either a copy of the temporary instance of A being bound to the B::a or that temporary itself being destructed during ~B().

基本上,我认为B :: a在b的生命周期中始终是有效的引用.实际上,b.print_data()显然可以工作,并且编译器不会发出任何警告.

Basically, I thought B::a is always a valid reference during the life of b. In fact b.print_data() works apparently and the compiler does not give any warning.

标准的c ++ 98/03对这件事怎么说?

What does the standard c++98/03 say about this matter?

推荐答案

恒定引用不会延长类,周期中的临时对象的寿命.就是这样他们只在 Foo const&中执行此操作f = Foo(); ,其中 foo 返回按值,仅此而已.

Constant references don't prolong the life of temporaries in classes, period. It's just like that. They only do it in Foo const& f = Foo(); where foo returns by-value, but that's it.

§12.2[class.temporary]

p4在两个上下文中,临时变量在与完整表达式末尾不同的位置被销毁.[...]

p4 There are two contexts in which temporaries are destroyed at a different point than the end of the full expression. [...]

p5第二个上下文是将引用绑定到临时项时.引用所绑定的临时对象或作为与该临时对象所绑定的子对象的完整对象的临时对象在引用的生存期内一直存在,除非以下指定.在构造函数的ctor-initializer(12.6.2)中,临时绑定到参考成员的行为会一直存在,直到构造函数退出为止..

p5 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 to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

这篇关于const引用数据成员,该成员绑定到构造函数中的该引用的临时初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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