Explicitly deleting a shared_ptr

meteoritepanama picture meteoritepanama · Sep 7, 2012 · Viewed 71.9k times · Source

Simple question here: are you allowed to explicitly delete a boost::shared_ptr yourself? Should you ever?

Clarifying, I don't mean delete the pointer held by the shared_ptr. I meant the actual shared_ptr itself. I know most people suggest to not do it, so I was just wondering if it's OK to explicitly do it.

Answer

Praetorian picture Praetorian · Sep 7, 2012

Your question isn't clear. If you've allocated a shared_ptr dynamically then you're certainly allowed to delete it whenever you want.

But if you're asking whether you're allowed to delete whatever object is being managed by the shared_ptr, then the answer is ... it depends. If shared_ptr::unique returns true, then calling shared_ptr::reset will delete the managed object. However, if shared_ptr::unique returns false, it means there are more than one shared_ptrs sharing ownership of that object. In this case a call to reset will only result in the reference count being decremented by 1, actual deletion of the object will take place when the last shared_ptr managing that object either goes out of scope or is itself reset.

EDIT:
After your edit, it seems you are asking about deleting a dynamically allocated shared_ptr. Something like this:

auto sp = new boost::shared_ptr<int>( new int(42) );

// do something with sp

delete sp;

This is allowed and will work as expected, although it would be an unusual use case. The only caveat is that if in between the allocation and deletion of sp you create another shared_ptr that shares ownership of the object, deleting sp will not result in deletion of the object, that will only happen when the reference count for the object goes to 0.