tags:

views:

611

answers:

2

See also: Similar question

The code below is obviously dangerous. The question is: how do you do keep track of the reference to *this?

using namespace boost;

// MyClass Definition
class MyClass {

public:
   shared_ptr< OtherClass > createOtherClass() {
      return shared_ptr< OtherClass > OtherClass( this ); // baaad
   }
   MyClass();
   ~MyClass();
};

// OtherClass Definition
class OtherClass {

public:
   OtherClass( const *MyClass myClass );
   ~OtherClass();
};

// Call; pMyClass refcount = 1
shared_ptr< MyClass > pMyClass( new MyClass() );

// Call; pMyClass refcount = 1 => dangerous
pMyClass->createOtherClass();

I have the answer (posted below), I just want it to be on stackoverflow (where everyone can correct me if I'm wrong.)

+3  A: 

The key is to extend enable_shared_from_this<T> and use the shared_from_this() method to get a shared_ptr to *this

For detailed information

using namespace boost;    

// MyClass Definition
class MyClass : public enable_shared_from_this< MyClass > {

public:
   shared_ptr< OtherClass> createOtherClass() {
      return shared_ptr< OtherClass > OtherClass( shared_from_this() );
   }
   MyClass();
   ~MyClass();
};

// OtherClass Definition
class OtherClass {

public:
   OtherClass( shared_ptr< const MyClass > myClass );
   ~OtherClass();
};

// Call; pMyClass refcount = 1
shared_ptr< MyClass > pMyClass( new MyClass() );

// Call; pMyClass refcount = 2
pMyClass->createOtherClass();
Ryan Emerle
+1 for article linking the explanation
Edison Gustavo Muenz
+2  A: 

A couple of problems:
Your code does not compile!!

Your code is not designed in a way that it stops abuse/incorrect usage:

MyClass            x;
SharedPtr<MyClass> y = x.createOtherClass();

Now what?
This seems like a perfectly good use case!

Martin York
Your 2nd point is right on. Linked article says "keep in mind that the object you call shared_from_this on must be owned by a shared_ptr object." Best to make ctor private and provide named constructor (static method) that returns shared_ptr<MyClass> to enforce correct creation.
Dan