问题描述
如果我的类不动态分配任何内存,我们需要一个虚拟析构函数吗?
Do we need a virtual destructor if my classes do not allocate any memory dynamically ?
例如
class A
{
private:
int a;
int b;
public:
A();
~A();
};
class B: public A
{
private:
int c;
int d;
public:
B();
~B();
};
在这种情况下,我们需要将A的析构函数标记为虚拟的吗?
In this case do we need to mark A's destructor as virtual ?
推荐答案
问题不在于你的类是否动态分配内存。这是如果类的用户通过A指针分配一个B对象,然后删除它:
The issue is not whether your classes allocate memory dynamically. It is if a user of the classes allocates a B object via an A pointer and then deletes it:
A * a = new B;
delete a;
在这种情况下,如果没有A的虚拟析构函数,C ++标准说你的程序展示未定义的行为。这不是一件好事。
In this case, if there is no virtual destructor for A, the C++ Standard says that your program exhibits undefined behaviour. This is not a good thing.
此行为在标准的5.3.5 / 3节中指定(这里指 delete
):
This behaviour is specified in section 5.3.5/3 of the Standard (here referring to delete
):
这篇关于虚拟析构函数:是不是动态分配内存时需要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!