使用weak_ptr打破shared_ptr循環引用

代碼示例:

struct B;

sruct A{

   ~A() { count <<" ~A()"<<endl;}

  boost::shared_ptr<B> b;

};

 

struct B{

  ~B() { count <<"~B()"<<endl;}

//  boost::shared_ptr<A> a; // 循環引用 不可用

  boost::weak_ptr<A> a ; //可以打破循環引用,在先聲明的B中用weak_ptr

};

 

int main()

{

   boost::shared_ptr<A> ap(new A);

   boost::shared_ptr<B> bp(new B);

  ap->b = bp;

  bp->a = ap;

 return 0;

}

 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章