Ryan Emerle
Ryan Emerle

Reputation: 15811

How should you return *this with a shared_ptr?

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.)

Upvotes: 6

Views: 3653

Answers (2)

Loki Astari
Loki Astari

Reputation: 264381

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!

Upvotes: 1

Ryan Emerle
Ryan Emerle

Reputation: 15811

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();

Upvotes: 8

Related Questions