Sign in to follow this  
hiigara

[C++] Smart Pointers with Polymorphic Objects

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this