我知道在C ++中为基类声明虚拟析构函数是一个好习惯,但是virtual即使对于充当接口的抽象类,声明析构函数也总是很重要吗?请提供一些原因和示例。
3 回答

哆啦的时光机
TA贡献1779条经验 获得超6个赞
对于界面而言,它甚至更为重要。该类的任何用户都可能持有指向该接口的指针,而不是指向具体实现的指针。当他们删除它时,如果析构函数不是虚拟的,他们将调用接口的析构函数(如果未指定,则为编译器提供的默认值),而不是派生类的析构函数。即时内存泄漏。
例如
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
- 3 回答
- 0 关注
- 1050 浏览
添加回答
举报
0/150
提交
取消