• Advertisement
Sign in to follow this  

[C++] Smart Pointers with Polymorphic Objects

This topic is 2819 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


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

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
Sign in to follow this  

  • Advertisement