boost::weak_ptr and shared_ptr pointers from "this"

D

Daniel T.

Rafa©© Maj Raf256 said:
How can I manually (other then
http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html)
create a shared, and a weak pointer to "this"?

Of course I dont want the shared / weak pointer to cause object to be
deleted when shared/weak ptr will go out of scope.

That's the major problem with shaired pointers IMO. I have a class that
doesn't have this problem. I store the reference counts in a map<void*,
int>

That way, both pointer objects in the code below increment the same
reference count.

class MyClass {
public:
void doThis() {
Ptr<MyClass> p( this );
// ...
}
};

void func( Ptr<MyClass> foo ) {
foo->doThis();
}
 
J

Joe Gottman

Rafal Maj Raf256 said:
How can I manually (other then
http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html)
create a shared, and a weak pointer to "this"?

Of course I dont want the shared / weak pointer to cause object to be
deleted when shared/weak ptr will go out of scope.

If you know that your object is long lived, you can do the following:

struct null_deleter
{
template <class T> void operator()(T *) {}
}

Then in your code, just return a shared_ptr<your_type>(this, null_deleter())

Joe Gottman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top