问题描述
父类有一个虚函数。是否有必要在父类中有一个虚拟析构函数?
Parent class has a Virtual function. Is it necessary to have a virtual destructor in the parent class ?
所以问题是
1.现在考虑规则三,我们应该声明另外两个?
So the questions are1. Now considering rule of three , should we declare the other two?
推荐答案
任何时候都需要一个虚拟析构函数。 delete
在指向该类的指针被调用,其中被删除的对象实际上是一个派生类型。如果你的基类可能在这种情况下使用,那么你必须提供一个虚拟析构函数。
A virtual destructor is required any time delete
is called on a pointer to that class where the object being deleted is actually of a more derived type. If your base class may be used in this sort of situation then you must provide a virtual destructor.
通常建议添加一个虚拟析构函数函数,因为这为类的未来用户提供了安全性和灵活性,并且向已经存在的多态类添加虚拟析构函数的额外成本通常较低。
It is usually advisable to add a virtual destructor to any class that has virtual functions as this gives safety and flexibility to future users of the class and the additional cost of adding a virtual destructor to an already polymorphic class is typically low.
只是一个经验的大拇指,虽然。可能有必要在类中有一个虚析构函数,即使它没有任何其他虚函数,反之,如果一个多态类不需要一个虚析构函数,如果它从不需要这个上下文通常,析构函数将被 protected
或甚至 private
强制实施)。
This last rule is just a rule of thumb, though. It may be necessary to have a virtual destructor in a class even if it doesn't have any other virtual functions and, conversely, a virtual destructor may not be needed for a polymorphic class if it is never used in a context that requires this (typically the destructor would be made protected
or even private
to enforce this).
你只需要提供一个用户定义的拷贝构造函数和一个拷贝赋值运算符,如果编译器提供的默认实现不会做正确的事情。如果你添加了一个带有空实现的析构函数,只是为了使它成为虚拟的,这不太可能对你提供一个拷贝构造函数和一个拷贝赋值运算符的需要有任何影响。
You only need to provide a user-defined copy constructor and a copy assignment operator if the compiler provided default implementations won't do the correct thing. If you've added a destructor with an empty implementation purely to make it virtual, this is unlikely to have any bearing on the need for you to provide a copy constructor and a copy assignment operator.
这篇关于父类有一个虚函数。是否有必要在父类中有一个虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!