c++ - 具有公共(public)非虚拟析构函数的类是否应标记为 "final"?

标签 c++ c++11

<分区>

要关闭选民,请帮助我改进问题以便重新打开:How can I improve this question so that it gets reopened?

赫伯萨特 wrote :

A base class destructor should be either public and virtual, or protected and nonvirtual.

根据该指南,如果您有一个带有公共(public)非虚拟析构函数的类,则不应将该类用作基类。 为什么不将其标记为 final 以强制执行?


但萨特也 wrote以下,暗示不需要使用 final:

Re "uses of final are rarer" - well, they sort of are. I don’t know of many, and during standardization Bjarne repeatedly asked for examples of problems it solved and patterns where it should be used, and I don’t recall any major ones that stood out.

Scott Meyer 的 Effective C++,第 7 项中的另一条相关引述暗示 final 现在可用,应该使用它:

If you're ever tempted to inherit from a standard container or any other class with a non-virtual destructor, resist the temptation! (Unfortunately, C++ offers no derivation-prevention mechanism akin to Java's final classes or C#'s sealed classes.)

另一个数据点是 standard library has no types marked "final" ,但这样做的原因似乎是为了避免破坏代码。

这里有一个类似的问题,但不完全重复,因为它遗漏了“protected, nonvirtual”选项:Default to making classes either `final` or give them a virtual destructor?

最佳答案

According to that guideline, if you have a class with a public non-virtual destructor, then that class shouldn't be used as a base class. Why not mark it final to enforce that?

因为它是一个适用于某些情况但不是所有情况的指南,所以您为什么“强制执行”它?

在尚未提供通过 virtual 函数调用的动态多态性的情况下,禁止继承非常好,但这不是我们使用继承的唯一场景。

C++ 是多范式,开始强制执行仅适合部分用例的狭窄方法没有意义。据我所知,您的建议基本上可以归结为禁止人们使用继承,除非他们也打算使用动态多态性。

关于c++ - 具有公共(public)非虚拟析构函数的类是否应标记为 "final"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810700/

相关文章:

c++ - 比较两组类型是否相等

c++ - Spirit X3 具有来自语义操作的 boost::string_ref 构造

c++ - 在 C++ 中如何在 arm 架构中检测 EOF

c++ - 为什么使用 std::mutex 的函数会对 pthread_key_create 的地址进行空检查?

c++ - 如果 make_shared/make_unique 可以抛出 bad_alloc,为什么为它设置一个 try catch block 不是一种常见的做法?

c++ - 方法超出范围后是否应该删除引用的 std::shared_ptr ?

c++ - 有没有办法告诉程序正在抛出异常?

c++ - 将值乘以 static_cast<uint8_t> 时如何确定 auto 的类型

c++ - boost any_range 性能:std::prev(iterator) 与 --iterator

c++ - 使用仅使用一次的变量调用的复制构造函数。这可能是通过调用 move 构造函数来优化编译器的情况吗?