0

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,

Community
  • 1
  • 1
Pavan Dittakavi
  • 3,013
  • 5
  • 27
  • 47

1 Answers1

2

This class ("mixin") is intended for classes that you know are going to need shared access. Instead of managing the shared_ptrs from outside the class, this allows the class to contain this information (that it is shared using shared_ptr) and thus avoid some common pitfalls.

When you used a share_ptr for something, a common pitfall is to initialize more than one share_ptr with the same raw pointer -

Bla *bla = new Bla;
shared_ptr<Bla> x(bla);
shared_ptr<Bla> y(bla);

This code has a bug, the two share_ptrs are not aware of each other and both will delete the pointer. If however you use this mixin, the class itself is responsible for managing its share_ptrs and this makes it impossible for this bug to occur since all share_ptrs of an instances are derived from the same source.
This is also why you would want the constructor to be private or protected. You don't want the user to be able to create instances of the class since that will allow him to write code like the above again.
The create function is an entry point for you, the class writer to instantiate the class. To call new and pass arguments to the constructor. boost doesn't want to call new for you since you might want to use an allocator or use a non-trivial c'tor.

shoosh
  • 76,898
  • 55
  • 205
  • 325