如何启用父级和派生的_shared_from_this [英] How to enable_shared_from_this of both parent and derived
问题描述
我有一个简单的基类和派生类,我都希望它们都具有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\n";
}
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\n";
}
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\n";
}
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<foo>
和shared_ptr<bar1>
是不同的类型.我不了解幕后发生的一切,但我认为,当构造函数返回并分配给shared_ptr<foo>
时,内部weak_ptr<bar1>
会看到没有指向它的内容(因为只有shared_ptr<bar1>
会增加计数器的值)并自行重置.当您在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!