为什么std::shared_ptr在赋值给另一个点时不表现得像原始点


#include <iostream>
#include <memory>
int main () {
std::shared_ptr<int> foo;
std::shared_ptr<int> bar (new int(10));
foo = bar;             
bar.reset(new int(20));
std::cout << "*foo: " << *foo << 'n';
std::cout << "*bar: " << *bar << 'n';
return 0;
}

输出:* foo: 10*栏:20

#include <iostream>
#include <memory>
int main () {
int * foo;
int *bar = new int(10);
foo = bar;
*bar = 20;
std::cout << "*foo: " << *foo << 'n';
std::cout << "*bar: " << *bar << 'n';
return 0;
}

输出:* foo: 20*栏:20

如何使shared_pt B从shared_pt A, B具有相同的内部值作为A,无论A更改以后(如上面的原始指针的例子)?

如果你做同样的事情,它们的行为是一样的

int main() {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar(new int(10));
  foo = bar;
  *bar = 20;
  std::cout << "*foo: " << *foo << 'n';
  std::cout << "*bar: " << *bar << 'n';
  std::cin.get();
  return 0;
}

相关内容

  • 没有找到相关文章

最新更新