为什么我应该为C ++中的抽象类声明虚拟析构函数? [英] Why should I declare a virtual destructor for an abstract class in C++?

查看:443
本文介绍了为什么我应该为C ++中的抽象类声明虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在C ++中为基类声明虚拟析构函数是一个好习惯,但是对于作为接口的抽象类,声明 virtual ?请提供一些原因和示例。

I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.

推荐答案

这对于界面更加重要。你的类的任何用户可能会保存一个指向接口的指针,而不是一个指向具体实现的指针。当它们删除它,如果析构函数是非虚拟的,他们将调用接口的析构函数(或编译器提供的默认,如果你没有指定一个),而不是派生类的析构函数。即时内存泄漏。

It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.

例如

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; 
}

这篇关于为什么我应该为C ++中的抽象类声明虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆