I love Boost's smart_ptr features and the ability to convert to and from a shared_ptr
and weak_ptr
, but since the reference count is not contained in the pointed class itself, the following code does not work (and it shouldn't).
A *a = new A;
shared_ptr<A> aPtr1(a);
{
shared_ptr<A> aPtr2(a);
// The reference counts of aPtr1 and aPtr2 are both 1.
} // At this point, `a` is destructed by aPtr2.
aPtr1->foo(); // And... SIGTERM
I believe the JUCE framework has this functionality. [ReferenceCountedObject
and ReferenceCountedObjectPtr
]
However, I'd rather use Boost for my application. Is it possible to allow Boost smart_ptrs to look for the reference count in the pointed class rather than the private boost::detail::shared_count
instance?
This is not exception safe:
Making them exception safe takes a bit more work. You will want to reimplement
make_shared
, but tag the resultingshared_ptr
with a cleanup function.Simple solution:
If you want something more complicated, see http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html :
Edit: I should have mentioned that
enable_shared_from_this
has some unfortunate issues with derivation. However, the following works with c++11; I didn't try it with boost but I suppose it should work there, too. I think it's a bit of a hack; using raw pointers when you use shared_ptr's is bound to end in tears:boost::intrusive_ptr likely fits your requirements.
To note however, with shared_ptr, you should construct them as follows: