另见:
Similar question
@H_403_2@下面的代码显然很危险.问题是:你如何跟踪* 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();@H_403_2@我有答案(在下面发布),我只想让它在stackoverflow上(如果我错了,每个人都可以纠正我.)
解决方法
关键是扩展enable_shared_from_this< T>并使用shared_from_this()方法将shared_ptr获取到* this
@H_403_2@For detailed information
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();