4

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

#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;
}

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

4

2 回答 2

5

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

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

You must also make sure that you don't use that reference after the container is destroyed. In this example, it's fine - m_member, and the reference it contains, are destroyed along with the container.

于 2012-04-11T17:03:59.040 回答
4

That's ok, but do note that container in Member's constructor is not completely constructed yet, so you can't do anything with it except store that reference.

于 2012-04-11T17:04:02.933 回答