加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使用shared_ptr返回* this?

发布时间:2020-12-16 03:47:13 所属栏目:百科 来源:网络整理
导读:另见: Similar question 下面的代码显然很危险.问题是:你如何跟踪* this的引用? using namespace boost;// MyClass Definitionclass MyClass {public: shared_ptr OtherClass createOtherClass() { return shared_ptr OtherClass OtherClass( this ); //
另见: Similar question

下面的代码显然很危险.问题是:你如何跟踪* 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

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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读