c++之析构函数中的动态转换
这个代码合法吗?
class Base1 {
};
class Base2 {
public:
virtual ~Base2() {
if (!dynamic_cast<Base1*>(this))
std::cout << "aaaa" << std::endl;
}
Base2() {
}
};
class MyClass: public Base1, public Base2 {
public:
MyClass() {
}
virtual ~MyClass() {
std::cout << "bbb" << std::endl;
}
};
int main() {
MyClass s;
return 0;
}
我看到了两张照片,但我应该只看到一张。我猜动态 Actor 是错误的。可以做这种检查吗?
请您参考如下方法:
也许我自己找到了解决方案,答案是否定的,这是不可能的:
来自 bullet 6 of cppreference.com documentation :
When dynamic_cast is used in a constructor or a destructor (directly or indirectly), and expression refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If new-type is not a pointer or reference to the constructor's/destructor's own class or one of its bases, the behavior is undefined.
另请参阅标准的 [class.cdtor]/6。
由于我在 Base2 析构函数中强制转换为 Base1,因此此行为未定义。
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。