【问题标题】:Using the reference to an object in the member initialzation list of its constructor在其构造函数的成员初始化列表中使用对对象的引用
【发布时间】:2012-04-11 17:01:13
【问题描述】:

是否可以在其构造函数的成员初始化列表中传递对对象(类型)Container 的引用,以便初始化Container 的成员,如下所示: (ideone 上的代码)。

#include <cstdlib>
#include <iostream>

struct Container;

struct Member
{
    Member( Container& container ) : m_container( container )
    {
    }

    Container& m_container;
};

struct Container
{
    Container() : m_member( *this )
    {
    }

    Member m_member;
};

int main()
{
    Container c;
    return EXIT_SUCCESS;
}

代码可以编译,但我不确定它是否标准。

【问题讨论】:

    标签: c++ constructor pass-by-reference


    【解决方案1】:

    没关系;成员引用被初始化为引用作为参数传递的对象。

    但是,由于Container 仍在构建中,因此您不能在该构造函数中访问它;对引用唯一能做的就是初始化另一个引用。

    您还必须确保在容器被销毁后不使用该引用。在此示例中,这很好 - m_member 及其包含的引用与容器一起被销毁。

    【讨论】:

      【解决方案2】:

      没关系,但是请注意Member 的构造函数中的container 尚未完全构造,因此除了存储该引用之外,您无法对其进行任何操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 2016-05-03
        相关资源
        最近更新 更多