Re: What is the rationale behind std::tr1::enable_shared_from_this?
ljestrada@hotmail.com wrote:
I'm trying to find the rationale behind this class beyond the Boost
documentation
(http://www.boost.org/libs/smart_ptr/sp_techniques.html#from_this) and
Pete Becker's C++ Standard Library Extensions book (section 2.6, pp
57).
I understand the technicalities of the class, but what are some
practical uses?
One practical use is shown in the example given at the link above.
Imagine that you need to implement an existing interface that is
specified to return a shared_ptr:
class Y
{
public:
virtual shared_ptr<X> getX() = 0;
protected:
~Y() {}
};
This isn't a problem if you create a new X-derived object in getX and
return a shared_ptr to it. If, however, you want to return a pointer to
'this' since the object you are writing happens to also implement the X
interface as well, you have a problem. Within a virtual member function
you have access to 'this' but you don't have access to a shared_ptr to
this. Since you are constrained by the existing interfaces, you can't
rearrange the code to give you the shared_ptr you need, so you have to
obtain it somehow from within getX. This is where
enable_shared_from_this comes in. It serves a very specific need. If
you don't see an use case for it in your design, don't feel obligated
to use it.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]