I don't understand C++ Primer explanation about virtual destructor

73 views Asked by At

I don't understand this phrase from the famous C++ Primer :

"classes used as the root of an inheritance hierarchy almost always define a virtual destructor."

I don't understand why the book doesn't say the destructor of a Base class must always be virtual.

If it's not and we write this (to use polymorphism) :

std::unique_ptr<Base> derived(new Derived);

We are sure to have an undefined behaviour.

Sometimes I feel like this book can be really misleading especially for C++ noob like me.

When I first read this book I didn't get Base classes must have a virtual destructor until SonarQube told me during a pull request.

1

There are 1 answers

2
lorro On

First, there are environments where you don't do dynamic memory allocation, but still can have class hierarchies, e.g. in embedded systems.

Second, while std::unique_ptr<> does not handle the case well, if you only use std::shared_ptr<>, then the pattern above will properly delete the object without a virtual destructor. This is because deleter for std::shared_ptr<> is captured at construction time (based on the class you specified). You could force the same behavior using a deleter in std::unique_ptr<>, but that's reflected in the type.