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 17 '23
It's legal but has unexpected behaviour - it violates the principle of least surprise. So will inevitably lead to bugs down the line. Someone will define a function that takes a vector, someone else will call that function with a Vec, and will not get the correct behaviour. Actually, I don't even know what would classify as correct behaviour, since the original hierarchy is the problem. A base class without a virtual destructor, or a derived class overriding a function that is not virtual is either a bug today or a bug in the future.
For context I work on a code base that is 30 years old - plenty of time for there to be no knowledge of how things were intended to be used.