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.)
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).
Passing as smartptr<T>&& (by move) imposes the pointer to be moved on call, by forcing you to explicitly use std::move (but requires "move" to make sense for the particular pointer).
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With