Herb Sutter wrote:
A base class destructor should be either public and virtual, or protected and nonvirtual.
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?
But Sutter also wrote the following, implying that final
need not be used:
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.
Another relevant quote, implying that final
should be used now that it's available, is from Scott Meyer's Effective C++, item 7:
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.)
Another data point is that the standard library has no types marked "final", but the reason for that seems to be to avoid breaking code.
There's a similar question here, but not exactly a duplicate as it misses the "protected, nonvirtual" option: Default to making classes either `final` or give them a virtual destructor?
Aucun commentaire:
Enregistrer un commentaire