用enable_shared_from_this在類的成員函數中獲得指向當向前對象的shared_ptr

下面的代碼編譯沒有問題,運行時錯誤。錯誤發生在void test1()銷燬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不會銷燬它指向的對象。
發佈了21 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章