我想了解当 shared_ptr 分配给另一个时,shared_ptr 中托管对象的引用计数如何受到影响。

我在 C++ 入门,第 5 版 中遇到了以下语句:



作为一个例子,它显示在那里:

auto p = make_shared<int>(42); // object to which p points has one user

auto q(p); // p and q point to the same object
           // object to which p and q point has two users

auto r = make_shared<int>(42); // int to which r points has one user
r = q; // assign to r, making it point to a different address
       // increase the use count for the object to which q points
       // reduce the use count of the object to which r had pointed
       // the object r had pointed to has no users; that object is automatically freed

当我运行类似的代码时,以上不是我的观察:

代码:
#include<iostream>
#include<memory>

int main()
{
  std::shared_ptr<int> sh1 = std::make_shared<int>(1);
  std::shared_ptr<int> sh2 = std::make_shared<int>(2);

  sh2 = sh1;

  std::cout << "sh1 use count: " << sh1.use_count() << std::endl;
  std::cout << "sh2 use count: " << sh2.use_count() << std::endl;

  return 0;
}


use_countsh2 怎么可能也是 2?根据上面提到的文本,它不应该是 0 吗?我在这里错过了什么吗?

最佳答案

起初你有 sh1.use_count=1sh2.use_count=1 。现在,当您使用 sh2=sh1 进行分配时,会发生以下情况:

  • sh2 计数器减一,因为 sh2(shared_ptr)将采用另一个指针
  • 从现在的sh2.use_count=0 开始,它的指针下的对象,也就是int(2) 被销毁了。
  • 现在您将 sh2 分配给了一个属于 sh1 的新对象,因此它的计数器加一,所以: sh2.use_count=2 ,当然还有 sh1.use_count=2 ,因为两个 shared_ptr 对象都指向同一个对象,即 int(1)
  • 关于c++ - 当创建 shared_ptr 的拷贝时会发生什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45411219/

    10-11 22:07