Possible Duplicate:
what is the usefulness of enable_shared_from_this
I want to have an idea of what shared pointers are. So, I googled and had some insight into them. And I ran into a website which provided brief overview of the smaprt pointer concept. However, I could not undesrtand what they wanted to convey with the following (or rather how to achieve it).
Shared pointers in member functions
Sometimes a shared pointer to the current object is needed in its member function. Boost provides a mixin template class called enable_shared_from_this, which defines a no-argument member function called shared_from_this(). It returns a shared pointer to this. At least one instance of a shared pointer to this object must exist before the first use of this method; otherwise it has undefined results (usually crash). The best way to guarantee that this is condition met is to make the constructor protected and provide a factory method that returns a shared pointer to the newly created object.
class Foo : public enable_shared_from_this<Foo> {
public:
void someMethod() {
boost::shared_ptr<Foo> this_ = shared_from_this();
// use pointer...
}
...
static boost::shared_ptr<Foo> create() {
return boost::shared_ptr<Foo>(new Foo());
}
protected:
Foo() { ... }
...
};
Could someone please let me know how can an object of this class be created and what role does the create() method play here? (im trying to figure this out as we speak..but just in case!:))
Thanks, Pavan,