[C++] Smart Pointers with Polymorphic Objects

Started by
2 comments, last by the_edd 13 years, 11 months ago
I intend to Store Objects of a derived Class as pointers to the Base Class, in a shared_ptr. Does this mean that I need a virtual Destructor in the Base?
Advertisement
Yes. In general, any class with virtual functions should have a virtual destructor. I would only be tempted to remove the virtual destructor if I had overwhleming proof that it was causing performance issues.

Such a scenario is extremely unlikely, and probably has more macro-optimisation opportunities available - you would have to be allocating them at a ferocious rate and allocation is also expensive.
Yes.
Quote:Original post by hiigara
I intend to Store Objects of a derived Class as pointers to the Base Class, in a shared_ptr. Does this mean that I need a virtual Destructor in the Base?


You should.

But actually boost::shared_ptr is in fact written in such a way that it isn't necessary, provided the shared_ptr is constructed in the correct manner.

Its constructor looks like this:

template<class T> class shared_ptr {    public:      template<class Y> explicit shared_ptr(Y * p);// ...};


So if you were to do the following, shared_ptr is actually smart enough to call the destructor of the derived class.

shared_ptr<Base> p(new Derived);


You can read the implementation to find out why and how this works (it's related to the fact that shared_ptrs have "deleter" objects and a default deleter will be based on the type of Y given to the constructor).

However, this isn't true for smart pointers in general so I wouldn't rely on it. Add a virtual destructor.

This topic is closed to new replies.

Advertisement