c++ - 制作 shared_ptr 的拷贝时会发生什么?

标签 c++ c++11 shared-ptr

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

我在 C++ primer, 5th edition 中看到以下声明:

For example, the counter associated with a shared_ptr is incremented when ... we use it as the right-hand operand of an assignment... The counter is decremented when we assign a new value to the shared_ptr...

举个例子:

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;
}

Output:

sh1 use count: 2

sh2 use count: 2

sh2use_count怎么也是2?根据上面提到的文字,它不应该是 0 吗?我在这里遗漏了什么吗?

最佳答案

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

  1. sh2 计数器减一,因为 sh2(shared_ptr)将采用另一个指针
  2. sh2.use_count=0 开始,其指针下的对象 int(2) 被销毁。
  3. 现在您将 sh2 分配给了一个属于 sh1 的新对象,因此它的计数器增加了 1,所以:sh2.use_count=2 ,当然还有 sh1.use_count=2,因为两个 shared_ptr 对象都指向同一个对象,即 int(1)

关于c++ - 制作 shared_ptr 的拷贝时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411219/

相关文章:

c++ - 依赖名称和范围

c++ - std::shared_ptr<X> 是否有复制构造函数?

c++ - 复制和粘贴 .so 文件不适用于链接器

c++ - 有一个 weak_ptr 的 vector ,想要返回一个 shared_ptr 的 vector

c++ - enable_shared_from_this 中的空弱指针

java - 使用通用方法?

c++ std::string.find 在 boolean 表达式中返回意外结果

c++ - 用于编码和解码 websocket 帧的 C 或 C++ 库

c++ - cpp 的函数式方法

c++ - 用于测试 uint64_t 和 unsigned long long int 之间差异的编译器宏