使用boost :: weak_ptr打破循环依赖关系的示例

q09*_*987 2 boost

我已经看到其中一个用法boost::weak_ptr是打破循环依赖.有人可以给我一个简单的具体例子来说明这个功能吗?

谢谢

Dre*_*ann 5

简单来说:

{  // Enter scope

  shared_ptr<A> my_a(new A);
  shared_ptr<B> my_b(new B);

  my_a->remember_this_b( my_b );  // Stores a copy of a smart pointer
  my_b->remember_this_a( my_a );  // Stores a copy of a smart pointer

} // Leave scope.  my_a and my_b are destroyed.
Run Code Online (Sandbox Code Playgroud)

如果这两个函数都存储了a shared_ptr,则永远不会删除对象,因为它们都shared_ptr不会达到零引用计数.

但是,如果任何一个使用了a weak_ptr,那么weak_ptr当离开范围时,将指向的对象将被销毁.而这反过来会破坏最后一个shared_ptr对象.