为什么weak_ptr可以打破循环引用?
我学到了很多关于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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
强指针持有对对象的强引用 - 意思是:只要指针存在,对象就不会被销毁。
该对象并不单独“知道”每个指针,只知道它们的编号 - 这就是强引用计数。
一种weak_ptr会“记住”该对象,但不会阻止它被销毁。您无法直接通过弱指针访问该对象,但您可以尝试从弱指针创建强指针。如果该对象不再存在,则生成的强指针为空:
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:
它不包含在引用计数中,因此即使存在弱指针也可以释放资源。当使用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.