gpt4 book ai didi

c++ - 虚拟析构函数在特定情况下的实际必要性

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:49 26 4
gpt4 key购买 nike

C++03 5.3.5.3

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

这是理论。然而,这个问题是一个实际的问题。如果派生类不添加数据成员怎么办?

struct Base{
//some members
//no virtual functions, no virtual destructor
};
struct Derived:Base{
//no more data members
//possibly some more nonvirtual member functions
};

int main(){
Base* p = new Derived;
delete p; //UB according to the quote above
}

问题:是否存在任何现有的实现,这真的很危险?如果是这样,您能否描述一下在导致此代码崩溃/泄漏或其他情况的实现中如何实现内部结构?我你相信,我发誓我无意依赖这种行为:)

最佳答案

一个示例是,如果您在 struct Derived 中提供自定义 operator new。显然调用错误的 operator delete 可能会产生毁灭性的结果。

关于c++ - 虚拟析构函数在特定情况下的实际必要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4365157/

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