Skip to main content
gamedev.net
🔒 Locked

boost::shared_ptr trickery

Started by Kekko 2 replies 800+ views
Original Post
Kekko
Kekko
I'm looking for solutions for a problem I have with boost::shared_ptr's. Let's see a pseudo-c++-example:


// 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...
}

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?
Telastyn
Telastyn
Care to restate this with the real problem? It's difficult to offer alternatives when we've no idea as to the needs or constraints.

Without more knowledge, I would lean towards a private/protected constructor and a BooPtr Boo::Create();
Kekko
Kekko
These are both perfect solutions for me.
I'm gonna go with the private/protected constructor, mostly for simplicity.
Thanks, both of you.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.