我有简单的基类和派生类,我希望它们都具有 shared_from_this()
.
I have simple base and derived class that I want both have shared_from_this()
.
这个简单的解决方案:
class foo : public enable_shared_from_this<foo> {
void foo_do_it()
{
cout<<"foo::do_it
";
}
public:
virtual function<void()> get_callback()
{
return boost::bind(&foo::foo_do_it,shared_from_this());
}
virtual ~foo() {};
};
class bar1 : public foo , public enable_shared_from_this<bar1> {
using enable_shared_from_this<bar1>::shared_from_this;
void bar1_do_it()
{
cout<<"foo::do_it
";
}
public:
virtual function<void()> get_callback()
{
return boost::bind(&bar1::bar1_do_it,shared_from_this());
}
};
在以下代码中导致异常tr1::bad_weak_ptr
:
Causes exception tr1::bad_weak_ptr
in following code:
shared_ptr<foo> ptr(shared_ptr<foo>(new bar1));
function<void()> f=ptr->get_callback();
f();
所以在谷歌搜索"之后,我找到了以下解决方案:
So after "googling" I have found following solution:
class bar2 : public foo {
void bar2_do_it()
{
cout<<"foo::do_it
";
}
shared_ptr<bar2> shared_from_this()
{
return boost::static_pointer_cast<bar2>(foo::shared_from_this());
}
public:
virtual function<void()> get_callback()
{
return boost::bind(&bar2::bar2_do_it,shared_from_this());
}
};
现在它可以工作了.
有没有更好、更方便、更正确的方法来为父母和孩子enable_shared_from_this
?
Is there any better and more convinient and correct way to enable_shared_from_this
for both parent and child?
谢谢
抱歉,没有.
问题在于 shared_ptr
和 shared_ptr
是不同的类型.我不了解幕后发生的一切,但我认为当构造函数返回并分配给 shared_ptr
时,内部 weak_ptr
看到没有任何东西指向它(因为只有 shared_ptr
会增加计数器)并重置自己.当您在 get_callback
中调用 bar1::shared_from_this
时,您会收到异常,因为内部 weak_ptr
没有指向任何内容.
The problem is that shared_ptr<foo>
and shared_ptr<bar1>
are different types. I don't understand everything that's going on under the hood, but I think that when the constructor returns and is assigned to a shared_ptr<foo>
, the internal weak_ptr<bar1>
sees that nothing is pointing to it (because only a shared_ptr<bar1>
would increment the counter) and resets itself. When you call bar1::shared_from_this
in get_callback
, you get the exception because the internal weak_ptr
isn't pointing to anything.
本质上,enable_shared_from_this
似乎只能从层次结构中的单个类透明地工作.如果您尝试手动实现,问题应该变得很明显.
Essentially, enable_shared_from_this
only seems to work transparently from a single class in a hierarchy. If you try implementing it manually, the problem should become obvious.
这篇关于如何启用父代和派生的_shared_from_this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!