gpt4 book ai didi

c++ - 析构函数中的动态转换

转载 作者:行者123 更新时间:2023-12-01 12:27:16 25 4
gpt4 key购买 nike

这个代码合法吗?

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,因此此行为未定义。

关于c++ - 析构函数中的动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973782/

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