Hi,
I'm still fairly new to C++ and I'm
in the process of converting pointers to boost shared pointers. I have
a question regarding the use of enable_shared_from_this.
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();
}
}
And then access m_ptr_this in classes
derived from someclass, and pass as a parameter to methods of other (derived
or non-derived) classes. eg.
class someclass2 : public someclass
{
...
some_func(){
someclass3* f = new someclass3();
someclass3->do_something( m_ptr_this );
}
}
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. 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.
I've also considered having a member
function return the pointer:
boost::shared_ptr<someclass> someclass::get_this()
{
return
shared_from_this();
}
and then calling the routine like this;
someclass3->do_something( get_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.
What I'm hoping to do is avoid having
to declare extra shared_ptr vars all over the place.
Any help will be most appreciated. And
I'll owe you a beer!
Regards
Ethann Castell