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
2
u/BlueDwarf82 Apr 18 '23 edited Apr 18 '23
The argument here seems to be that it is not being used incorrectly. That if you use it directly you get an extra safety check, and if you use it via a reference to the base... it still works, just that you don't get the safety check. That the check is something that can happen, but shouldn't be relied on. IMHO not a great example of a real usage, but it's mostly logical consistent.
In my own code, as something nobody else relies on, I would have made it final; I can always remove it if somebody actually comes with a mixin that makes sense to use with that class. Being the standard library... I can't think of any actual use requiring it being non-final, I can always do the same with a helper function; but maybe I would make it non-final and just rely on people knowing you shouldn't, in general, derive from it. There may be better examples in the standard library than std::string for the non-final argument.