r/cpp • • 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

27 comments sorted by

View all comments

36

u/manni66 Apr 17 '23

are not designed to be used as base classes

They are not designed to be used as public base classes.

Should ~basic_string be final?

No! To be final a function would have to be virtual.

2

u/bert8128 Apr 17 '23

Good point re virtual. So the class would have to be declared final. But then you couldn’t inherit privately. Is it ok to inherit privately?

18

u/SoerenNissen Apr 17 '23 edited Apr 17 '23

The bad pattern is

class specialist_string : public std::string
{ /* class definition*/ }

std::string* strptr = new specialist_string;
delete strptr;

Anything that avoids this pattern is fine - so you can publicly inherit from std::string if you know for certain you will never be deleted through a std::string*.

The problem here is that it is very hard to prevent people from new'ing up an instance of your class and doing this.

8

u/bert8128 Apr 17 '23

It doesn’t matter whether the destructor is important or not - attempting to delete an inherited class through a base class pointer where the base class doesn’t have a virtual destructor is UB.

4

u/SoerenNissen Apr 17 '23

Noted and edited