【发布时间】:2011-03-08 12:52:07
【问题描述】:
我有一个接受shared_ptr<MyClass> 的函数。
在MyClass 的某些成员函数memfun 中,我需要将this 传递给该函数。但是如果我写
void MyClass:memfun()
{
func(shared_ptr<MyClass>(this))
}
我假设调用结束后引用计数将达到 0,并且将尝试销毁 this,这很糟糕。
然后我记得有这个类 enable_shared_from_this 和函数 shared_from_this。
所以现在我将使用以下内容:
class MyClass: public enable_shared_from_this<MyClass>
{
void MyClass:memfun()
{
func(shared_from_this());
}
};
问题是:
1) 如果不从 enable_shared_from_this 派生,绝对不可能使用该功能吗?
2) 从 enable_shared_from_this 派生是否意味着调用 memfun具有自动存储期限的对象会导致不好的事情吗?例如
int main()
{
MyClass m; //is this OK?
m.memfun(); // what about this?
}
3) 如果我从 MyClass 派生,enable_shared_from_this 功能会被正确继承还是需要再次派生?也就是说,
class MyCoolClass: public Myclass
{
void someCoolMember
{
someCoolFuncTakingSharedPtrToMyCoolClass(shared_from_this());
}
}
这样好吗?或者正确的是以下?
class MyCoolClass: public Myclass, public enable_shared_from_this<MyCoolClass>
{
void someCoolMember
{
someCoolFuncTakingSharedPtrToMyCoolClass(enable_shared_from_this<MyCoolClass>::shared_from_this());
}
}
非常感谢。
【问题讨论】:
标签: c++ shared-ptr