6

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

Community
  • 1
  • 1
Ryan Emerle
  • 15,461
  • 8
  • 52
  • 69
  • 1
    Not sure why this is being voted down.. from the FAQ: It's also perfectly fine to ask and answer your own programming question [..] – Ryan Emerle Apr 29 '09 at 12:39
  • The downvote may well have been because the code you have posted in the question won't compile. –  Apr 29 '09 at 12:59
  • Unfortunately, the point was not to provide compilable code but, instead, to illustrate the point with unnecessary details elided. – Ryan Emerle Apr 29 '09 at 14:19
  • It doesn't even illustraete the point. Unless you show what OtherClass does with the pointer in its constructor, the question is meaningless. –  Apr 29 '09 at 14:43

2 Answers2

7

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
  • 15,461
  • 8
  • 52
  • 69
1

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
  • 257,169
  • 86
  • 333
  • 562
  • 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 to enforce correct creation. – Dan Apr 29 '09 at 20:54