c++ - 具有非虚拟析构函数的派生类

标签 c++

在任何情况下派生类具有非virtual 析构函数是合法的吗?非virtual 析构函数表示不应将类用作基类。派生类的非virtual析构函数会像Java final修饰符的弱形式吗?

我对派生类的基类有virtual析构函数的情况特别感兴趣。

最佳答案

Are there any circumstances in which it is legitimate for a derived class to have a non-virtual destructor?

是的。

A non-virtual destructor signifies that a class should not be used as a base-class.

不是真的;非虚拟析构函数表示通过 base 指针删除 derived 的实例将不起作用。例如:

class Base {};
class Derived : public Base {};

Base* b = new Derived;
delete b; // Does not call Derived's destructor!

如果不按上述方式进行delete,那就可以了。但如果是这种情况,那么您可能会使用组合而不是继承。

Will having a non-virtual destructor of a derived class act like a weak form of the Java final modifier?

不,因为 virtual-ness 会传播到派生类。

class Base
{
public:
    virtual ~Base() {}
    virtual void Foo() {};
};

class Derived : public Base
{
public:
    ~Derived() {}  // Will also be virtual
    void Foo() {}; // Will also be virtual
};

在 C++03 或更早版本中没有内置的语言机制来防止子类 (*)。反正这不是什么大问题,因为你应该总是 prefer composition over inheritance .也就是说,当“is-a”关系比真正的“has-a”关系更有意义时,使用继承。

(*) 'final' 修饰符是在 C++11 中引入的

关于c++ - 具有非虚拟析构函数的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7403883/

相关文章:

C++ 通过引用传递 : how is the call stack used?

c++ - boost::asio 的段错误,带有 deadline_timer 的异步 udp-server

c++ - 将数组传回主体

c++ - 在没有组合的情况下对嵌套的 boost::bind 执行参数替换

c++ - 相同的线程 ID

c++ - (MATLAB/C++) 是否可以将函数作为参数传递给 C++ MEX 函数?

c++ - 奇怪的食人魔错误和一个不存在的文件

c++ - 如何在子类和父类之间添加槽?

c++ - 确定 C++ 中包含文件的编译时存在

c++ - 你什么时候担心堆栈大小?