gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:51:42 29 4
gpt4 key购买 nike

我学到了很多关于 weak_ptr 与 share_ptr 一起使用来打破循环引用的知识。它是如何工作的?如何使用它?任何人都可以给我一个例子吗?我完全迷失在这里。

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

最佳答案

强指针持有对象的强引用——意思是:只要指针存在,对象就不会被销毁。

对象不“知道”每个指针,只知道它们的编号——这就是强引用计数。

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

关于c++ - 为什么 weak_ptr 可以打破循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374719/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com