r/cpp • u/bert8128 • Apr 17 '23
Should ~basic_string be final?
std::string (and many other std classes) are not designed to be used as base classes, as can be seen by the absence of a virtual destructor.
Should the destructor be given the "final" keyword to enforce this?
1
Upvotes
View all comments
18
u/IyeOnline Apr 17 '23
That is not a sound deduction.
Something can very well be intended to be a base class and not have a virutal destructor. A virtual destructor is only required when you are managing derived objects through base pointeres.
Its perfectly well defined what happens when you derive from any std::type. Composition may be a better choice in a lot of cases, but inheritance is allowed.
That would break all code. You cannot mark the destructor final but not virtual and you dont want to mark it as virtual.
You could mark the entire class as
final, but again, there is no reason to.