Hi, I would like to store a self-referencing pointer within the object.
Something like:
class someclass : public boost::enable_shared_from_this<someclass> { protected: boost::shared_ptr<someclass> m_ptr_this; someclass() { m_ptr_this = shared_from_this(); } }
A self-referencing smart pointer within your object is not necessary if you are using enable_shared_from_this. By calling shared_from_this() you can obtain a shared_ptr to this when you need it. Otherwise you are creating a vicious circle and your reference count will never reach zero again. Please note that enable_shared_from_this requires the existence of at least one shared_ptr instance that owns your object. That is, before you are allowed to call shared_from_this() your object has to be under control of a smart pointer. That's why you cannot use shared_from_this in the object's constructor. It's very important to understand this point correctly. I recommend to create a factory function for your class: class someclass { ... public: shared_ptr<someclass> CreateSomeClass() { shared_ptr<someclass> p(new someclass); return p; } } I understand that using a shared_ptr (without enable_shared_from_this) to
self-reference will lead to problems because the reference count of the pointer will never reach zero and therefore the memory will never get released.
Yes, that's correct and is true for enable_shared_from_this, too. But as enable_shared_from_this uses a weak pointer internally, does this
get around the problem? I'm getting a little confused because it gets typecast from weak_ptr to shared_ptr and I'm not sure what this leads to.
As enable_shared_from_this relies on at least one external reference to *this a weak pointer is sufficient.
boost::shared_ptr<someclass> someclass::get_this() { return shared_from_this(); }
but I think that this will cause a problem because the documentation says not to use boost pointers which are only created as temporary variables. i.e. store all boost pointers in vars.
In this case the shared_ptr is not temporary because there's already a shared_ptr (an external one) which owns the object. Best regards, Philipp