将引用引用到基类的构造函数会导致未定义的行为吗?

时间:2014-11-25 12:08:51

标签: c++ design-patterns

在实施一些设计思路时,我偶然发现了一些奇怪的行为,我无法自己解释。

查看以下示例,该示例已使用MSVC2010进行编译。

struct A
{
    void helloMe()
    {
        std::cout << "hej da!\n";
    }
};

struct B
{
    B(A& a): 
        m_a(a)
        {
            std::cout << "B got constructed!\n"; 
        }

A& m_a;
};

struct C : A, B 
{
    C() : 
        A(),
        B(*this)
        { std::cout << "C got constructed!\n";
        }
};

int _tmain() 
{

    C c;
    c.m_a.helloMe();

    std::cin.get();
    return 0;
}

这编译无错误,但在执行时,从不调用B的构造函数。也就是说,在尝试访问m_a时,我遇到了段错误。但是当显式转换为*reinterpret_cast<A*>(this)时,构造函数将按预期调用。

那么为什么上面的例子不起作用,但是我需要明确地演绎?这是编译器相关的问题吗?

编辑:

所以使用强制转换它看起来像:

struct A
{
    void helloMe()
    {
        std::cout << "hej da!\n";
    }
};

struct B
{
    B(A& a): 
        m_a(a)
        {
            std::cout << "B got constructed!\n"; 
        }

A& m_a;
};

struct C : A, B 
{
    C() : 
        A(),
        B(*reinterpret_cast<A*>(this))
        { std::cout << "C got constructed!\n";
        }
};

int _tmain() 
{

    C c;
    c.m_a.helloMe();

    std::cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

正如jrok所指出的,这是一个编译器错误。编译器无法识别复制构造函数和显式构造函数的模糊调用。 此外,static_cast<A*>本来是正确的选择。

事实上,根据标准,演员阵容是必要的,而MSVC2010缺乏标准的符合行为。它只调用复制构造函数而不考虑实际声明的复制构造函数。因此可能发生段错误。在明确声明复制构造函数private时,您会注意到复制构造函数调用。然后MSVC2010抱怨。

感谢您的评论。