如果我有一个带有虚拟析构函数的基类.是否有派生类也要声明虚析构函数?
If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too?
class base {
public:
virtual ~base () {}
};
class derived : base {
public:
virtual ~derived () {} // 1)
~derived () {} // 2)
};
具体问题:
final
来防止它在派生类中被覆盖,但这并不能防止它成为虚拟的.virtual
关键字或 override
.人们不应该一直向上继承层次结构来确定函数是虚拟的.此外,如果您的类是可复制或可移动的,而无需声明您自己的复制或移动构造函数,则声明任何类型的析构函数(即使您将其定义为 default
)将迫使您声明副本和如果需要,请移动构造函数和赋值运算符,因为编译器将不再为您放置它们.final
to prevent it from being overridden in derived classes, but that doesn't prevent it from being virtual.virtual
keyword or override
for virtual functions in derived classes for reasons of clarity. People shouldn't have to go all the way up the inheritance hierarchy to figure out that a function is virtual. Additionally, if your class is copyable or movable without having to declare your own copy or move constructors, declaring a destructor of any kind (even if you define it as default
) will force you to declare the copy and move constructors and assignment operators if you want them as the compiler will no longer put them in for you.作为第 3 条的一个小点.在评论中已经指出,如果析构函数未声明,编译器会生成一个默认的(仍然是虚拟的).并且默认的是一个内联函数.
As a small point for item 3. It has been pointed out in comments that if a destructor is undeclared the compiler generates a default one (that is still virtual). And that default one is an inline function.
内联函数可能会将程序的更多部分暴露给程序其他部分的更改,并使共享库的二进制兼容性变得棘手.此外,增加的耦合会导致在面对某些类型的更改时进行大量重新编译.例如,如果你决定你真的想要一个虚拟析构函数的实现,那么调用它的每一段代码都需要重新编译.而如果您已在类主体中声明它,然后在 .cpp
文件中将其定义为空,则无需重新编译就可以更改它.
Inline functions potentially expose more of your program to changes in other parts of your program and make binary compatibility for shared libraries tricky. Also, the increased coupling can result in a lot of recompilation in the face of certain kinds of changes. For example, if you decide you really do want an implementation for your virtual destructor then every piece of code that called it will need to be recompiled. Whereas if you had declared it in the class body and then defined it empty in a .cpp
file you would be fine changing it without recompiling.
我个人的选择仍然是尽可能省略它.在我看来,它会使代码变得混乱,并且编译器有时可以使用默认实现而不是空实现来做更高效的事情.但是,您可能会受到一些限制,使之成为一个糟糕的选择.
My personal choice would still be to omit it when possible. In my opinion it clutters up the code, and the compiler can sometimes do slightly more efficient things with a default implementation over an empty one. But there are constraints you may be under that make that a poor choice.
这篇关于虚拟析构函数是继承的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!