shared_ptrで* thisをどのように返す必要がありますか?
-
03-07-2019 - |
質問
関連項目:同様の質問
以下のコードは明らかに危険です。問題は、* thisへの参照をどのように追跡するかです。
using namespace boost;
// MyClass Definition
class MyClass {
public:
shared_ptr< OtherClass > createOtherClass() {
return shared_ptr< OtherClass > OtherClass( this ); // baaad
}
MyClass();
~MyClass();
};
// OtherClass Definition
class OtherClass {
public:
OtherClass( const *MyClass myClass );
~OtherClass();
};
// Call; pMyClass refcount = 1
shared_ptr< MyClass > pMyClass( new MyClass() );
// Call; pMyClass refcount = 1 => dangerous
pMyClass->createOtherClass();
答えがあります(以下に投稿)、私はそれがstackoverflowにあるようにしたいだけです(間違っていれば誰でも私を修正することができます)
解決
キーは、enable_shared_from_this<T>
を拡張し、shared_from_this()
メソッドを使用してshared_ptrを*this
using namespace boost;
// MyClass Definition
class MyClass : public enable_shared_from_this< MyClass > {
public:
shared_ptr< OtherClass> createOtherClass() {
return shared_ptr< OtherClass > OtherClass( shared_from_this() );
}
MyClass();
~MyClass();
};
// OtherClass Definition
class OtherClass {
public:
OtherClass( shared_ptr< const MyClass > myClass );
~OtherClass();
};
// Call; pMyClass refcount = 1
shared_ptr< MyClass > pMyClass( new MyClass() );
// Call; pMyClass refcount = 2
pMyClass->createOtherClass();
他のヒント
いくつかの問題:
コードはコンパイルされません!!
あなたのコードは、悪用/不正な使用を防ぐようには設計されていません:
MyClass x;
SharedPtr<MyClass> y = x.createOtherClass();
今何?
これは完全に良いユースケースのようです!
所属していません StackOverflow