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

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。它更明确一些。

https://stackoverflow.com/questions/47556287/

相关文章:

c++ - 为什么 reinterpret_cast 不能将 int 转换为 int?

c++ - 与 win32 CRITICAL_SECTION 相比的 std::mutex 性能

c++ - 什么是 decltype 以及它是如何使用的?

c++ - "&s[0]"是否指向 std::string 中的连续字符?

c++ - 三元表达式中的逗号混淆

c++ - Visual Studio 没有为此文档加载任何符号

c++ - 如何将 vector::push_back()` 与结构一起使用?

c++ - 编译lua代码,存储字节码然后加载并执行

c++ - auto 和 decltype 的关系

c++ - vector 的 std::remove 和删除之间的区别?