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

发布于 2024-08-23 21:20:12 字数 109 浏览 10 评论 0原文

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

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

I learnt a lot about weak_ptr working with share_ptr to break cyclic reference. How does it work? How to use that? Can any body give me an example? I am totally lost here.

One more question, what's a strong pointer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独难免 2024-08-30 21:20:12

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

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

一种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

A strong pointer holds a strong reference to the object - meaning: as long as the pointer exists, the object does not get destroyed.

The object does not "know" of every pointer individually, just their number - that's the strong reference count.

A weak_ptr kind of "remembers" the object, but does not prevent it from being destroyed. YOu can't access the object directly through a weak pointer, but you can try to create a strong pointer from the weak pointer. If the object does nto exist anymore, the resulting strong pointer is null:

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
镜花水月 2024-08-30 21:20:12

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

Q2:shared_ptr是强指针。只要其中任何一个存在,资源就无法被释放。

It is not included in the reference count, so the resource can be freed even when weak pointers exist. When using a weak_ptr, you acquire a shared_ptr from it, temporarily increasing the reference count. If the resource has already been freed, acquiring the shared_ptr will fail.

Q2: shared_ptr is a strong pointer. As long as any of them exist, the resource cannot be freed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文