c++ - 析构函数可以是最终的吗?

标签 c++ c++11 inheritance destructor

C++ 标准是否允许将析构函数声明为 final?像这样:

 class Derived: public Base
 {
      ...
      virtual ~Derived() final;
 }

如果是这样,那是否会阻止派生类的声明:

 class FurtherDerived: public Derived {// allowed?
 }

如果允许,编译器是否可能发出警告?将析构函数声明为 final 是否是一个可行的习惯用法,用于指示一个类不打算用作基类?

(有no point in doing this in a ultimate base class,只有派生类。)

最佳答案

May a C++ destructor be declared as final?

是的。

And if so, does that prevent declaration of a derived class:

是的,因为派生类必须声明一个析构函数(由您显式或由编译器隐式),并且该析构函数将覆盖声明为 final 的函数,该函数格式错误.

规则是[class.virtual]/4 :

If a virtual function f in some class B is marked with the virt-specifier final and in a class D derived from B a function D​::​f overrides B​::​f, the program is ill-formed.

这是不正确的推导本身,它不必使用。

Is declaring a destructor to be final a workable idiom for indicating that a class is not intended to be used as a base class?

有效,但您应该只标记类 final。它更明确一些。

关于c++ - 析构函数可以是最终的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556287/

相关文章:

c++ - 重写 push_back C++

c++ - 处理请求的策略设计模式

c++ - 一个图书馆强制我在全局范围内重载新的/删除的!

python - 在python中覆盖类变量

class - 为什么我不能制作单独的表格副本?

c++ - 为什么要求自定义分配器是可复制构造的?

C++ 友元函数从命名空间内部引用全局枚举

c++ - 在c中如何在没有 vector 和结构数组的情况下拥有可变数量的结构?

c++ - 函数中的 r 值参数

c++ - 在定义重载C++函数模板的原型(prototype)时,使用它的名字来引用之前的定义是否合法?