且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++“接口"是否应具有虚拟析构函数

更新时间:2022-11-09 22:41:14

您应始终将虚拟析构函数与接口一起使用.恰当的例子:

You should always use a virtual destructor with interfaces. Case in point:

IAnimal* animal = new Lion();
delete animal;

现在它将使用什么析构函数?绝对不是Lion的析构函数,因为接口不知道Lion的析构函数.

Now what destructor is it going to use? Definately not the Lion's destructor because the interface doesn't know about Lion's destructor.

因此,如果您的界面没有内存管理,请执行以下操作:

So, have this if your interface has no memory management:

virtual ~IAnimal(){}