boost::enable_shared_from_this why?

Hello, reading the documentation for enable_shared_from_this, I can't understand why this kind of base class is needed. In the example code in the documentation, we have: class Y: public enable_shared_from_this<Y> { public: shared_ptr<Y> f() { return shared_from_this(); } } int main() { shared_ptr<Y> p(new Y); shared_ptr<Y> q = p->f(); assert(p == q); assert(!(p < q || q < p)); // p and q must share ownership } Isn't this piece of code equivalent (since the two pointers share ownership): class Y { }; int main(int argc, char * argv[]) { shared_ptr<Y> p(new Y); shared_ptr<Y> q(p); ... }

Imagine you have to acquire shared_ptr to the object from within its member
function. How would you do this without shared_from_this()?
Anyway, which is the reason to access a variable through a member function if you can get the variable directly anyway? Or is there any case where you can't?
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users

Anyway, which is the reason to access a variable through a member function if you can get the variable directly anyway? Or is there any case where you can't?
The code you quoted is just trivial example of "how to use shared_from_this()", not "why to use it". If you want to realise *why* such a feature can be useful, look, for instance, at ASIO examples: http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial/tutdaytime... Actually, there're lots of cases where you might want to make shared_ptr of "this" inside a member function.
participants (2)
-
Germán Diago
-
Igor R