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

前端之家收集整理的这篇文章主要介绍了c – 如何使用shared_ptr返回* this?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
另见: Similar question

下面的代码显然很危险.问题是:你如何跟踪* this的引用?

  1. using namespace boost;
  2.  
  3. // MyClass Definition
  4. class MyClass {
  5.  
  6. public:
  7. shared_ptr< OtherClass > createOtherClass() {
  8. return shared_ptr< OtherClass > OtherClass( this ); // baaad
  9. }
  10. MyClass();
  11. ~MyClass();
  12. };
  13.  
  14. // OtherClass Definition
  15. class OtherClass {
  16.  
  17. public:
  18. OtherClass( const *MyClass myClass );
  19. ~OtherClass();
  20. };
  21.  
  22. // Call; pMyClass refcount = 1
  23. shared_ptr< MyClass > pMyClass( new MyClass() );
  24.  
  25. // Call; pMyClass refcount = 1 => dangerous
  26. pMyClass->createOtherClass();

我有答案(在下面发布),我只想让它在stackoverflow上(如果我错了,每个人都可以纠正我.)

解决方法

关键是扩展enable_shared_from_this< T>并使用shared_from_this()方法将shared_ptr获取到* this

For detailed information

  1. using namespace boost;
  2.  
  3. // MyClass Definition
  4. class MyClass : public enable_shared_from_this< MyClass > {
  5.  
  6. public:
  7. shared_ptr< OtherClass> createOtherClass() {
  8. return shared_ptr< OtherClass > OtherClass( shared_from_this() );
  9. }
  10. MyClass();
  11. ~MyClass();
  12. };
  13.  
  14. // OtherClass Definition
  15. class OtherClass {
  16.  
  17. public:
  18. OtherClass( shared_ptr< const MyClass > myClass );
  19. ~OtherClass();
  20. };
  21.  
  22. // Call; pMyClass refcount = 1
  23. shared_ptr< MyClass > pMyClass( new MyClass() );
  24.  
  25. // Call; pMyClass refcount = 2
  26. pMyClass->createOtherClass();

猜你在找的C&C++相关文章