gpt4 book ai didi

c++ - 这个菱形继承(钻石问题) UB 是 MinGW 中的错误吗?

转载 作者:可可西里 更新时间:2023-11-01 13:57:45 26 4
gpt4 key购买 nike

#include <iostream>
#include <sstream>

class VeryBase {
protected:
int a_;
public:
VeryBase() : a_(1) {}
virtual operator std::string() {
return "0";
}
};

class Base1 : public virtual VeryBase {
protected:
int b_;
public:
Base1() : b_(2) {}
operator std::string() {
return "1";
}
};

class Base2 : public virtual VeryBase {
protected:
int c_;
public:
Base2() : c_(3) {}
operator std::string() {
return "2";
}
};

class TargetClass : public Base1, public Base2 {
protected:
int d_;
public:
TargetClass() : d_(4) {}
operator std::string() {
std::ostringstream s;
s << a_ << ' ' << b_ << ' ' << c_ << ' ' << d_ << std::endl;
return s.str();
}
};

int main()
{
VeryBase* a = new TargetClass;
Base1* b = dynamic_cast<Base1*>(a);
Base2* c = dynamic_cast<Base2*>(a);

std::cout << std::string(*a) //1 2 3 4
<< std::string(*b) //1 2 3 4
<< std::string(*c) //? ? ? ?
<< std::endl;
}

我有这样的代码。它与 Windows 8 下的 MSVC 2012 x64、Ubuntu 12.10 和 13.04 下的 g++ 4.7 和 Clang++ 3.2(x86 和 x64)一起正常工作。但是,当使用 MinGW 4.7 x86 或 MinGW 4.8 x64 编译时,带有问号的行显示未定义的行为(抱歉,我以为我做到了)。

调试器输出表明此时链接到 TargetClass 的 vtable 存在问题。放置断点表明 TargetClass::operator string() 加载了严重解除引用的对象。但是,显式设置 dynamic_cast 会产生正确的输出。

我想知道什么可能导致这个问题。如果是MinGW的bug,估计一出现就解决了,因为它打破了C++的核心概念之一。

最佳答案

这是 mingw gcc 的一个已知问题。

不要使用虚拟继承,问题就会消失。

错误追踪器 http://sourceforge.net/p/mingw/bugs/1679/

关于c++ - 这个菱形继承(钻石问题) UB 是 MinGW 中的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16866925/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com