boost::shared_ptr and this

As a good introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Let's say we have a class A, and we want to call from one of its methods a free function that accept as input parameter a shared_ptr to A.

There is a relatively simple way to get it. We could let our class A derive from enable_shared_from_this<A> and use shared_from_this() to get the shared_ptr.

Here is a short example that shows this feature:

#include <iostream>
#include "boost/shared_ptr.hpp"
#include "boost/enable_shared_from_this.hpp"

using std::cout;
using std::endl;
using boost::shared_ptr;
using boost::enable_shared_from_this;

class A;
void doStuff(shared_ptr<A> p);

class A : public enable_shared_from_this<A>
void callDoStuff()
cout << "in A::callDoStuff()" << endl;

void cheers() { cout << "Cheers from A" << endl; }

void doStuff(shared_ptr<A> p)
cout << "Doing stuff in doStuff()" << endl;

void sharedThis()
shared_ptr<A> p(new A());

No comments:

Post a Comment