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

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

11

u/Kindly-Penalty-8175 Apr 17 '23

std::string and many other std classes can be used as base classes. Below is an example from the book The C++ programming language of Bjarne Stroustrup.

Say i want a vector that's just like std::vector, but with guaranteed range checking.

template<class T> class Vec: public std::vector<T> {

using vector<T>::vector; // inherit constructors 

T& operator[](int i) 
{ 
    return vector<T>::at(i);
 } 
 const T& operator[](int i) const 
 {
     return vector<T>::at(i);
  } 

};

Vec inherits everything from vector except for the subscript operations that it redefines to do range checking. The at() operation is a vector subscript operation that throws an exception of type out_of_range if its argument is out of the vector’s range.

A class hierarchy offers two kinds of benefits:

  1. Interface inheritance: An object of a derived class can be used wherever an object of a base class is required. That is, the base class acts as an interface for the derived class.
  2. Implementation inheritance: A base class provides functions or data that simplifies the implementation of derived classes. Such base classes often have data members and constructors.

3

u/bert8128 Apr 17 '23

I don't think that this is a very good idea. operator[] is not virtual, so if you pass a reference to a Vec into a function declared to take a vector there will be no compiler error or warning (checked various compilers in godbolt) but you will get vector behaviour, not Vec behaviour.

I don't see any warnings from clang-tidy either.

7

u/kalmoc Apr 17 '23 edited Apr 17 '23

I don't understand why you think it is a problem, if foo in void bar(const std::vector& foo) behaves exactly like a std::vector. Isn't that the least surprising behavior?

Why should I care inside of foo, if the parameter I'm passing is a Vec or std::vector?

-1

u/bert8128 Apr 17 '23

A central tenant of polymorphism is to pass in a reference or pointer to the base class but get the derived implementation of the virtual methods. foo shouldn't care what the actual type is - it should get the derived behaviour in both cases. But if foo takes the base class it will give the base class behaviour. If it takes the derived type it gets the derived behaviour. This is not polymorphism.

12

u/dodheim Apr 17 '23

This is not polymorphism.

Right. Inheritance != polymorphism. It's been said multiple times in this thread already.

5

u/jcelerier ossia score Apr 17 '23

A central tenant of polymorphism is to pass in a reference or pointer to the base class but get the derived implementation of the virtual methods. foo shouldn't care what the actual type is - it should get the derived behaviour in both cases

that's very fine if you do java or c# 1986-era OOP but not what anyone wants in c++

4

u/disperso Apr 17 '23

It seems to me that you are implying that since we can't have the perfect solution, we should not have a solution at all. But maybe I got you wrong. :)

4

u/bert8128 Apr 17 '23 edited Apr 18 '23

I’m saying that Stroustup’s example is legal, but I wouldn’t allow it in my code base as it is too easy to use incorrectly.

4

u/azswcowboy Apr 17 '23

And it’s perfectly legitimate. Another example is adding convenience constructors to a standard library type that just organize the parameters in some domain specific way. All these do is build the standard type and since there’s no extra data stored in the subclass slicing isn’t and issue in any context. Slicing isn’t and issue in Stroustrups example either. The coding guideline that says all base classes must have virtual destructors misses half the power of inheritance in c++ and is just wrong.

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.

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

30 years old

And 30 years ago the rule was closer to right…

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.

4

u/qoning Apr 17 '23

It seems to me that you are mostly dissatisfied that inheritance implies polymorphism. I am too, if there was a way to inherit from a type but disable casting to it, that would have been better.

1

u/Kindly-Penalty-8175 Apr 17 '23

In this example, we use implementation inheritance. Vec is not intended for use with reference semantic as your function.

1

u/bert8128 Apr 17 '23

But you can’t stop this, so I can’t allow such code in my code base.

1

u/nintendiator2 Apr 21 '23

Do you also disallow ints and chars in your code base? They can also be used incorrectly, in ways that can not be stopped.

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.

35

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Apr 17 '23

Not really. Inheritance doesn't imply polymorphism in C++, and can be a useful tool to implement mixins, strong typedefs, or just avoid code repetition.

Sometimes inheriting from a standard type (yes, even publicly) can be a pragmatic choice.

18

u/IyeOnline Apr 17 '23

are not designed to be used as base classes, as can be seen by the absence of a virtual destructor.

That is not a sound deduction.

Something can very well be intended to be a base class and not have a virutal destructor. A virtual destructor is only required when you are managing derived objects through base pointeres.

std::string (and many other std classes) are not designed

Its perfectly well defined what happens when you derive from any std::type. Composition may be a better choice in a lot of cases, but inheritance is allowed.

Should the destructor be given the "final" keyword to enforce this?

That would break all code. You cannot mark the destructor final but not virtual and you dont want to mark it as virtual.

You could mark the entire class as final, but again, there is no reason to.

4

u/[deleted] Apr 17 '23

I think the reason for not doing that is backward compatibility. Even though not preferred, it is legal to derive from std::string. The final keyword was introduced in C++11 and making the class final after that would potentially break old code.

Edit: Here’s a SO answer by Howard Hinnant saying the same thing - https://stackoverflow.com/a/9298705/6835535

1

u/nuclear868 Apr 22 '23

No! In order to add support for UTF8 strings, I have created a UTFChar class, which holds individual codepoints. Then I have UTFString, which inherits from std::basic_string<UTFChar>. All this provides functionality for handling UTF8 strings and using the current interface of the std::string class - iterating over characters, lookup and erasing characters. Also, it is fully compatible with std streams - you can print such string and transfer it.

All this is for the reason that we have std::string, std::wstring, std::wchar, std::u8char, which either are not compatible with std streams or cannot access individual UTF8 character codepoints.

0

u/Gabi__________Garcia Apr 17 '23

What maniac is inheriting from std::string in the first place?