应该是一个抽象类吗?析构函数是纯虚拟的吗?
我认为单独虚拟通常就足够了。
除了强制派生类实现自己的析构函数之外,还有其他原因使其成为纯虚拟的吗?我的意思是,如果您在类的构造函数中分配了某些内容,则应该实现自己的析构函数 - 如果您的类是派生的或不。
正如我已经知道的那样,这不算是答案:如果您想要您的类抽象并且它没有纯虚函数 - 将其留给析构函数。
还有一些用途吗?
I think virtual alone is generally sufficient.
Is there another reason to make it pure virtual than to force derived classes to implement their own destructor? I mean if you allocate something in your class' constructor you should impement your own destructor - if your class is derived or not.
Doesn't count as answer as I already know: If you want your class abstract and it has no pure virtual functions - leave it to the destructor.
Some more uses?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
事实上,我不认为还有更多。纯虚析构函数所做的就是使整个类抽象。您必须提供纯虚析构函数以及非纯虚析构函数的实现,派生类的析构函数是单独的虚析构函数,等等。
基本上,如果一个类已经有一些纯虚函数,那么它的行为与虚拟和纯虚拟析构函数等效。
Actually, I don't think there's more. All the pure virtual destructor does, is make the whole class abstract. You have to provide the implementation for the pure virtual destructor as well as for a non-pure virtual destructor, the destructors of the derived classes are virtual with virtual destructor alone, etc.
Basically, if a class has already some pure virtual functions, its behaviour would be equivalent with virtual and pure-virtual destructor.
不。如果基类分配了任何东西,它就有责任释放它。
此外,如果派生类没有分配任何内容,则没有必要强迫它们编写虚拟 dtor。
No. If the base class allocates anything, it is it's responsiblity to release it.
Further, if the derived class does not allocte anything, there's no point in forcing them to write a dummy dtor.
理想情况下,语言应该有一种方法来确保(隐式或非隐式)析构函数在抽象类中是虚拟的,而不必定义它或使其成为纯析构函数。但事实并非如此。
所以选择是:要么让它变得纯粹,并有在每个派生类中定义它的负担,要么不让它变得纯粹,并有在抽象类中定义它的负担。后者的工作量更少,代码也更短,所以我会选择它。
Ideally the language should have a way to assure (implicitly or not) that the destructor is virtual in abstract classes without having to define it or make it pure. But it hasn't.
So the choice is: either make it pure, and have the burden of defining it in each derived class, or make it not, and have the burden of defining it in the abstract class. The later is less work, and also shorter code, so I'd go for it.
如果您的抽象类是一个纯接口,没有数据成员,那么您可以将 dtor 设为纯虚拟。我自己更喜欢这一点,因为我见过很多优秀的程序员根本忘记创建虚拟析构函数:即使他们编写包含虚拟方法的派生类。
所以我这样做纯粹是为了减少以后的维护麻烦。
If your abstract class is a pure interface, with no data members than you could get along with making the dtor pure virtual. I prefer that myself, since I've seen so many hot-shot programmers forget to make a virtual destructor at all: Even when they write derived classes containing virtual methods.
So I would do it purely to minimize maintenance headaches down the road.