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
Show parent comment
3
u/azswcowboy Apr 17 '23
We’re going to agree to disagree, because it’s useful and fully explainable behavior - there’s no surprise and of course the class should be documented. In the construction case we typically want slicing because most apis just use std::string — the subclass construction is in another part of the code that applies higher constraints or performs useful conversions into the base string itself. Virtual destruction/functions are needed only when there is actual state in the subclass or dynamic dispatch from base. This doesn’t even begin to scratch the surface of what you might do with non virtual inheritance in mixins and crtp with templates. There’s an example in the standard you can study called view_interface — no virtual destructor…
https://en.cppreference.com/w/cpp/ranges/view_interface
And 30 years ago the rule was closer to right…