私は単純な基底と派生したクラスを持っていますが、両方とも持っているのはshared_from_this()
です。親と派生の両方を有効にする方法
このシンプルなソリューション:
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());
}
};
そして今、それを:私は解決策次を発見した "グーグル" の後にそう
shared_ptr<foo> ptr(shared_ptr<foo>(new bar1));
function<void()> f=ptr->get_callback();
f();
:
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
原因働く
enable_shared_from_this
には、親と子の両方にとってより便利で正しい方法がありますか?
ありがとうございました
私はそれを手動で実行する試みたが、それは実際には難しいことではありません。 'My :: SmartPointer'では、Tが 'My :: enableSmartFromThis'から派生しているかどうかをチェックします。もしそうなら、ヒープ上に参照カウンターを割り当てず、 'My :: enableSmartFromThis'のメンバーを使用してください。これで 'My :: GetSmartFromThis(this)'は簡単になり、 'this ::'を 'My :: enableSmartFromThis *'に変換して既存の参照カウントを見つけることができます。 Derivedのみが 'My :: enableSmartFromThis'から派生したときにBaseからDerivedに変換しようとしているかどうかを確認することもできます。 –
MSalters