为什么weak_ptr可以打破循环引用?

sky*_*oor 10 c++ smart-pointers

我学习了很多关于使用share_ptr来破坏循环引用的weak_ptr.它是如何工作的?怎么用?任何身体都可以举个例子吗?我完全迷失在这里.

还有一个问题,什么是强指针?

pet*_*hen 9

强指针保存对对象的强引用 - 意思是:只要指针存在,对象就不会被破坏.

对象不会单独"知道"每个指针,只是它们的数字 - 这是强引用计数.

weak_ptr类"记住"对象,但不会阻止它被破坏.你不能通过弱指针直接访问对象,但你可以尝试从弱指针创建一个强指针.如果对象不再存在,则生成的强指针为空:

shared_ptr<int> sp(new int);
weak_ptr<int> wp(sp);

shared_ptr<int> stillThere(wp);
assert(stillThere);  // yes, the original object still exists, we can now use it
stillThere.reset();  // releasing the strong reference

sp.reset();          // here, the object gets destroyed, 
                     // because there's only one weak_ptr left

shared_ptr<int> notReally(wp);
assert(!notReally);  // the object is destroyed, 
                     // you can't get a strong pointer to it anymore
Run Code Online (Sandbox Code Playgroud)


Tro*_*nic 6

它不包含在引用计数中,因此即使存在弱指针也可以释放资源.使用weak_ptr时,从中获取shared_ptr,暂时增加引用计数.如果资源已被释放,则获取shared_ptr将失败.

Q2:shared_ptr是一个强指针.只要它们中的任何一个存在,就无法释放资源.