Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual destructors only in selected bases

Tags:

c++

c++14

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 ? )

like image 861
Nikos Athanasiou Avatar asked Mar 22 '15 23:03

Nikos Athanasiou


People also ask

Do all base classes need virtual destructors?

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.

Are destructors virtual by default?

The destructor is not virtual (that is, the base class destructor is not virtual) All direct base classes have trivial destructors.

In which case the virtual destructor must be there in the base class?

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.

When should virtual destructors be used?

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.


1 Answers

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.

like image 184
R Sahu Avatar answered Oct 10 '22 03:10

R Sahu