当在初始化中使用此指针并且在层次结构中存在虚拟继承时,C++11 内联对象初始化不起作用(在 GCC 中)。 这可能是 GCC 的错误吗(因为它在 CLang 中工作)?还是 C++11 标准本身的差距?
示例(可以在 here 中尝试),当使用 GCC 编译以下代码时:
FieldIndex m_inB{"inB", this};
不会被执行。 但它会在使用 CLang 编译时执行。
变通方法:从 FieldIndexContainer
派生 A 作为虚拟
#include <string.h>
#include <iostream>
#include <list>
using namespace std;
class FieldIndexContainer
{
public:
class FieldIndex
{
public:
FieldIndex( const std::string& fieldName, FieldIndexContainer* owner)
{
cout << "FieldIndex called = " << fieldName << endl;
}
};
};
class A : public FieldIndexContainer
{
public:
FieldIndex m_inA{ "inA", this};
};
class Mid : virtual public A {};
class B : virtual public Mid
{
public:
FieldIndex m_inB{"inB", this};
};
int main ()
{
B* b = new B;
return 0;
}
最佳答案
您的 MCVE 可以进一步降低。
不需要 class Mid
。 class B
可以virtual public
继承自class A
问题依然存在。
除了您提出的从 FieldIndexContainer
派生 A
作为 的解决方法之外virtual
,代码也在没有任何virtual
继承的情况下也能正常工作。
参见 Live Demo 1 .
通过成员初始化,代码可以正常工作,无需任何变通方法。
参见 Live Demo 2 .
所以,这是一个 GCC 错误。
有一个针对 GCC 的错误报告,标题为:Missing default initialization of member when combined with virtual inheritance这与您在代码中观察到的非常相似。
关于c++ - 海湾合作委员会 : C++11 inline object initialization (using "this") does not work when there is a virtual inheritance in hierarchy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55273704/