Original Post
I'm looking for solutions for a problem I have with boost::shared_ptr's. Let's see a pseudo-c++-example: This is the problem I encountered. Both doStuff and the Boo constructor need a SmartPtr. There are a few solutions to this, but I'm not really happy with them. Perhaps attachBooToList or doStuff could take a normal pointer. But since both of them keep the reference to Boo for quite a while, it kinda defeats the purpose of having shared_ptr's in the first place. You could attachBooToList just after the constructor (in doStuff), but I don't want the user of Boo to have to know who Boo attaches to. Perhaps doStuff could get a shared_ptr from the BooList that Boo attaches itself to, but then doStuff has to know who Boo attaches to, just like above. You could send a shared_ptr to an init() function, but it annoys me to send a pointer to an object pointing to itself. It's not very elegant. Still, it's the best I can come up with. Using intrusive_ptr with a custom reference counting could perhaps solve the problem, but I don't want to run around making different custom reference counters for different classes. I think this problem will appear at many places. Is there another, better, solution to this?
// Boo.h
typedef boost::shared_ptr<Boo> BooPtr;
// Somewhere.cpp
void doStuff()
{
BooPtr ptr(new Boo());
// stuff...
}
// Boo.cpp
Boo::Boo()
{
// attachBooToList requires a shared_ptr.
attachBooToList( BooPtr(this) ); // Now we have two reference counts. Bad...
// stuff...
}