Search code examples
c++boostshared-ptr

shared_ptr chain/branch with a second deleter


I have a situation where I need to know when the user of a shared_ptr is done, that is, when the user has finally released all copies of it. Normally one just uses a deleter here, but there is a small catch in this case. The underlying object is already a shared_ptr!

That is, in pseudo-code:

shared_ptr<T> a( new T );
.
.
.
shared_ptr<T> b( a, bind( delete_func, id ) );

I'm spawning a new branch of sorts from the original shared_ptr. This new shared_ptr b may be copied and used like a normal shared_ptr but the delete_func must be called when this particular branch is done. Now, I can't just use a.get() here either since this new shared_ptr must retain the underlying object as well (it may be the last shared_ptr for it).

I'm looking for some way to do this without having to drastically change the framework. Does anybody see a good simple solution?

I'm using the boost library for smart pointers and bind.


Solution

  • I came up with one possible solution.

    Create a deleter function like this:

    void delete_func( int id, shared_ptr<T> underlying );
    

    Then to chain the shared_ptr do this:

    shared_ptr<T> b( a.get(), bind( &delete_func, id, a ) );
    

    This creates a new unattached shared_ptr with a custom deleter (my branch). One of the parameters is the original shared_ptr, thus this should maintain the underlying shared_ptr object as well. Now I just need to test this a bit.