用enable_shared_from_this在类的成员函数中获得指向当向前对象的shared_ptr

来源:互联网 发布:假面骑士555知乎 编辑:程序博客网 时间:2024/04/29 10:35
下面的代码编译没有问题,运行时错误。错误发生在voidtest1()销毁ptr时,认为ptr是最后一个指向A对象的shared_ptr,于是它试图销毁此对象。按理说main函数中有一个shared_ptr指向A的对象,那么test1()因该不会销毁ptr指向的对象。单步跟踪后,发现test1()::ptr的use_count_等于1(我认为因该是2)。
  1. // class A
  2. #include <boost/shared_ptr.hpp>
  3. #include "B.h"
  4. using namespace boost;
  5. class B;
  6. class A
  7. {
  8. public:
  9.   A()
  10.   {
  11.     mB = NULL;
  12.     mI = 1;
  13.   }
  14.   ~A()
  15.   {
  16.     if( NULL!=mB )
  17.     {
  18.       delete mB;
  19.     }
  20.   }
  21. void test1()
  22.   {
  23.     shared_ptr <A> ptr(this);
  24.     B b(ptr);
  25.     b.print();
  26.   }
  27. };
  28. //class B
  29. #include <boost/shared_ptr.hpp>
  30. #include <iostream>
  31. using namespace boost;
  32. using namespace std;
  33. class A;
  34. class B
  35. {
  36. public:
  37.   B(shared_ptr <A> a)
  38.   {
  39.     A* a_ptr=a.get();
  40.     mAshptr = a;
  41.   }
  42.   B(A* a)
  43.   {
  44.     mAptr = a;
  45.   }
  46.   B(A& a){mAptr=&a;}
  47.   ~B()
  48.   {
  49.   }
  50.   void print()
  51.   {
  52.     cout < <"BB" < <endl;
  53.   }
  54. private:
  55.   shared_ptr <A> mAshptr;
  56.   A* mAptr;
  57. };
  58. //main.cpp
  59. #include "A.h"
  60. int main()
  61. {
  62.   shared_ptr <A> ptr(new A());
  63.   ptr->test1();
  64. }
使用enable_shared_from_this
  1. #include <boost/shared_ptr.hpp>
  2. #include <boost/enable_shared_from_this.hpp>
  3. #include "B.h"
  4. using namespace boost;
  5. class B;
  6. class A : public enable_shared_from_this <A>
  7. {
  8. public:
  9.   A()
  10.   {
  11.     mB = NULL;
  12.     mI = 1;
  13.   }
  14.   ~A()
  15.   {
  16.     if( NULL!=mB )
  17.     {
  18.       delete mB;
  19.     } 
  20.   }
  21. void test1()
  22.   {
  23.     shared_ptr <A> ptr = shared_from_this();
  24.     B b(ptr);
  25.     b.print();
  26.   }
  27. }; 
单步跟踪发现A::test1()调用shared_from_this()后A::test1()::ptr的use_count_等于2,所以test1()::ptr不会销毁它指向的对象。
原创粉丝点击