11

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

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

4

2 回答 2

10

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

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

一种 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
于 2010-03-03T20:44:34.633 回答
6

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

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

于 2010-03-03T20:36:55.760 回答