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