按值传递共享指针使得在 mac 上计数为 0,在 win 上计数为 1

问题描述 投票:0回答:1

我看到共享指针按值传递在 mac 上计数为 0,但在我的代码中在窗口上仍为 1。
所以我一直试图通过听演讲reference talk来理解共享指针按值传递和按引用传递。这是在其他一些堆栈溢出链接中引用的here

我尝试通过在这里编码来理解基础知识https://godbolt.org/z/1vd53eEhM

#include <iostream>
#include <iostream>
#include <memory>

using namespace std;

void f(shared_ptr<int> sp) {
  
  ///sp.reset();
}

int main() {
  // Create a shared pointer.
  shared_ptr<int> sp = make_shared<int>(10);

  // Pass the shared pointer to the function by value.
  f(sp);

  // The original shared pointer has lost ownership of the object.
  cout << "testing (should be 0) "<< sp.use_count() << endl; // Prints 0

  return 0;
}

预期输出应该是 0,但我得到的结果是 1。

我错过了按价值传递所有权部分的损失吗?

c++ shared-ptr
1个回答
0
投票
// The original shared pointer has lost ownership of the object.

不,没有。 当调用

f(sp);
时,
sp
会被复制,因此原始
sp
f
中的副本共享所有权。 暂时,
use_count()
2

当您稍后打印

sp.use_count()
时,
sp
的副本不再存在,但
sp
仍然存在并且并未失去其所有权。 在
sp.reset()
内调用
f
也不会影响
sp
内的原始
main

仅当您移动(而不是复制)时才会失去所有权

sp

f(std::move(sp)); // the sp parameter object gains ownership, and our sp loses ownership
© www.soinside.com 2019 - 2024. All rights reserved.