I have a function which takes a shared_ptr<MyClass>.
In some member function memfun of MyClass, I need to pass this to that function. But if I write
void MyClass:memfun()
{
func(shared_ptr<MyClass>(this))
}
I am assuming that after the call has ended the reference count will reach 0 and this will be attempted to be destroyed, which is bad.
Then I remembered that there this class enable_shared_from_this with the function shared_from_this.
So now I am going to use the following:
class MyClass: public enable_shared_from_this<MyClass>
{
void MyClass:memfun()
{
func(shared_from_this());
}
};
Questions are:
1) Is is absolutely impossible to use the functionality without deriving from enable_shared_from_this?
2) Does deriving from enable_shared_from_this mean that calling memfun on an object with automatic storage duration will result in something bad? E.g.
int main()
{
MyClass m; //is this OK?
m.memfun(); // what about this?
}
3) If I derive from MyClass, will the enable_shared_from_this functionality be correctly inherited or do I need to derive again? That is,
class MyCoolClass: public Myclass
{
void someCoolMember
{
someCoolFuncTakingSharedPtrToMyCoolClass(shared_from_this());
}
}
Is this OK? Or correct is the following?
class MyCoolClass: public Myclass, public enable_shared_from_this<MyCoolClass>
{
void someCoolMember
{
someCoolFuncTakingSharedPtrToMyCoolClass(enable_shared_from_this<MyCoolClass>::shared_from_this());
}
}
Thanks very much in advance.
1) It depends on what you mean by “do this” as to whether or not you can. You can always construct a
shared_ptrfrom a raw pointer such asthis, but it won’t share the reference count with anothershared_ptrinstance that was separately constructed from a raw pointer. You will thus need to use a custom deleter on one or other instance to avoid double deletions, but unless you take great care then you may end up with danglingshared_ptrinstances due to the object being deleted through one, but still accessible from another.shared_from_thisenables you to guarantee that if you have oneshared_ptrinstance to your object then you can construct another without copying the first, and that these instances will share the reference count. You could achieve this by storing aweak_ptras a class member, and setting that value when you first allocate ashared_ptrto your object.2) Calling
shared_from_this()requires that there is at least oneshared_ptrinstance already pointing to your object. If you use it on an automatic object without ashared_ptrinstance with a custom deleter then you will get bad stuff happening.3) If you derive from your class then the
enable_shared_from_thisfunctionality will give you ashared_ptrto the base class (the one that derived fromenable_shared_from_this). You could then usestatic_pointer_castordynamic_pointer_castto cast the result ofshared_from_this()to a pointer to the derived class.