您的析构函数什么时候应该是虚拟的? [英] When should your destructor be virtual?

查看:110
本文介绍了您的析构函数什么时候应该是虚拟的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
何时使用虚拟析构函数?

Possible Duplicate:
When to use virtual destructors?

您的C ++对象的析构函数何时应为virtual?

When should your C++ object's destructor be virtual?

推荐答案

  1. 在以下位置需要虚拟析构函数 类方法中的至少一种是 虚拟的.
  1. You need virtual destructor when at least one of class methods is virtual.

这是因为使用虚拟方法的原因是您要使用多态性.这意味着您将在基类指针上调用一个方法,并且想要最派生的实现-这就是多态性的全部要点.

This is because the reason for virtual method is that you want to use polymorphism. Meaning you will call a method on the base class pointer and you want the most derived implementation - this is the whole point of polymorphism.

现在,如果您没有虚拟析构函数,并且通过指向基类的指针调用了析构函数,那么您最终将调用基类析构函数.在这种情况下,您还希望多态性也可以在您的析构函数上使用,例如通过在基类上调用析构函数,您希望最终调用最派生类而不是基类的析构函数.

Now if you did not have virtual destructor and through the pointer to base class you call destructor you end up calling base class destructor. In this case you want polymorphism to work on your destructor as well, e.g. through calling destructor on your base class you want to end up calling destructor of your most derived class not your base class.

class A
{
   virtual void f() {}
   ~A() {}
}

class B : public A
{
   void f() {}
   ~B() {}
}

A * thing = new B();
thing->f(); // calls B's f()
delete thing; // calls ~A(), not what you wanted, you wanted ~B()

具有〜A()虚拟可开启多态性

having ~A() virtual turns on polymorphism

virtual ~A() {}

因此,当您现在致电

delete thing;

〜B()将被调用.

在将类设计为接口时,您将声明虚拟析构函数.您希望它得到扩展或实施.在这种情况下,一种好的做法是使用虚拟方法和虚拟析构函数创建一个接口类(就Java接口而言),然后使用具体的实现类.

You would declare virtual destructors when you design class as an interface e.g. you expect it to be extended or implemented. A good practice in that case is to have a interface class (in the sense of Java interfaces) with virtual methods and virtual destructor and then have concrete implementation classes.

您可以看到STL类没有虚拟析构函数,因此不应该对其进行扩展(例如std :: vector,std :: string ...).如果扩展std :: vector并通过指针或引用在基类上调用析构函数,则绝对不会调用可能导致内存泄漏的专用类析构函数.

You can see that STL classes don't have virtual destructors so they are not supposed to be extended (e.g. std::vector, std::string ...). If you extend std::vector and you call destructor on base class via pointer or reference you will definitely not call your specialized class destructor which may lead to memory leaks.

这篇关于您的析构函数什么时候应该是虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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