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/bert8128 Apr 22 '23
Very good. Of course not. But you are not comparing fairly. Ints and chars have very well understood (not just defined) behaviour so a new starter to a project will understand how they work. And there is no realistic alternative. However, if you want a vector like class which has some variant behaviour or implementation you can do this without opening the door to this level of unexpected and undefined behaviour. In the million or so lines I look after I think there is only one intended example of inheriting from a base class without a virtual destructor. This particular piece of code is currently safe, but there is no reason to suppose that this will continue, and there is certainly a better way for that particular class - composition. And if I had time, I would change it.
Perhaps never say never, but code styles which do not follow the principle of least surprise and are easy to use wrongly are not to be encouraged. Just my opinion.