This is a cornercase not covered by this (although interesting info is provided therein). My code looks like the following :
struct concept {
virtual ~concept() = default;
};
struct policy {
protected :
~policy() = default;
};
struct implementation final : concept, policy {
};
If I'm only using this hierarchy through pointers to concept
:
unique_ptr<concept> = make_unique<implementation>();
is the above safe ?
I believe it is because if someone attempted to delete via a pointer to policy
the protected
destructor wouldn't allow it (a trick from Modern C++ design
) but does the rest work fine? (namely when the pointer to concept is deleted are the destructors of the hierarchy guaranteed to be called correctly ? )
If you are not going to delete object through a pointer to its base class - then there is no need to have a virtual destructor.
The destructor is not virtual (that is, the base class destructor is not virtual) All direct base classes have trivial destructors.
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
Virtual destructors in C++ are used to avoid memory leaks especially when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects. A destructor can be virtual.
Since ~concept()
is virtual, when you delete
the object via a concept
pointer, it will call ~implementation()
.
I don't see any reason why the rest will not work like they are supposed to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With