Search code examples
c++shared-ptr

Deleting content of a boost::shared_ptr


I have a doubt with boost::shared_ptr.

I have seen this in a destructor (with ptr being a boost::shared_ptr): ptr = boost::shared_ptr< int >( new int ).

Is that ok?. Shouldn't it be ptr.reset(), like stated here: How to intentionally delete a boost::shared_ptr?

Cheers!.


Solution

  • It depends what you want to do with ptr afterwards.

    If you need to reassign it to point to a new value, then that's what the code does. If you need to explicitly invalidate it, then that's what reset() does. If it's a class member that will be implicitly destroyed by the destructor, then there's probably no need to do anything, unless you have some weird destruction order requirements.

    Without more context, it's impossible to say which is correct.

    UPDATE: since you say this is not actually in a destructor, but a member function intended to leave the object in a weird half-destroyed state, it depends on how that weird state is specified. If it requires an empty pointer, then reset it; if it requires a valid pointer, but not to whatever was previously being shared, then reassign it. Better still, eliminate this state entirely to give the object stronger validity guarantees.