如何enable_shared_from_this既parend和衍生 [英] How to enable_shared_from_this of both parend 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
在以下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&LT;富&GT;
和的shared_ptr&LT; BAR1&GT;
是不同的类型。我不明白的引擎盖下发生的一切,但我的认为的,当构造函数返回并分配给的shared_ptr&LT;富&GT;
,内部的weak_ptr&LT; BAR1&GT;
认为没有什么指向它(因为只有的shared_ptr&LT; BAR1&GT;
将增加柜台),并自动复位。当你调用 BAR1 :: shared_from_this
在 get_callback
,你得到的异常,因为内部的的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
似乎只能从一个类层次结构中透明地工作。如果您尝试<一个href=\"http://www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#from%5Fthis\">implementing它手动的,这个问题应该成为显而易见的。
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.
这篇关于如何enable_shared_from_this既parend和衍生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!