下面的代码编译没有问题,运行时错误。错误发生在void test1()销毁ptr时,认为ptr是最后一个指向A对象的shared_ptr,于是它试图销毁此对象。按理说main函数中有一个 shared_ptr指向A的对象,那么test1()因该不会销毁ptr指向的对象。单步跟踪后,发现test1()::ptr的use_count_ 等于1(我认为因该是2)。
使用enable_shared_from_this
单步跟踪发现A::test1()调用shared_from_this()后A::test1()::ptr的use_count_等于2,所以test1()::ptr不会销毁它指向的对象。
- // class A
- #include <boost/shared_ptr.hpp>
- #include "B.h"
- using namespace boost;
- class B;
- class A
- {
- public:
- A()
- {
- mB = NULL;
- mI = 1;
- }
- ~A()
- {
- if( NULL!=mB )
- {
- delete mB;
- }
- }
- void test1()
- {
- shared_ptr <A> ptr(this);
- B b(ptr);
- b.print();
- }
- };
- //class B
- #include <boost/shared_ptr.hpp>
- #include <iostream>
- using namespace boost;
- using namespace std;
- class A;
- class B
- {
- public:
- B(shared_ptr <A> a)
- {
- A* a_ptr=a.get();
- mAshptr = a;
- }
- B(A* a)
- {
- mAptr = a;
- }
- B(A& a){mAptr=&a;}
- ~B()
- {
- }
- void print()
- {
- cout < <"BB" < <endl;
- }
- private:
- shared_ptr <A> mAshptr;
- A* mAptr;
- };
- //main.cpp
- #include "A.h"
- int main()
- {
- shared_ptr <A> ptr(new A());
- ptr->test1();
- }
- #include <boost/shared_ptr.hpp>
- #include <boost/enable_shared_from_this.hpp>
- #include "B.h"
- using namespace boost;
- class B;
- class A : public enable_shared_from_this <A>
- {
- public:
- A()
- {
- mB = NULL;
- mI = 1;
- }
- ~A()
- {
- if( NULL!=mB )
- {
- delete mB;
- }
- }
- void test1()
- {
- shared_ptr <A> ptr = shared_from_this();
- B b(ptr);
- b.print();
- }
- };