为什么std :: shared_ptr在分配给另一个时表现不像原始点?

时间:2014-06-26 06:20:23

标签: c++ std smart-pointers

#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中创建shared_pt B一个B具有与A相同的内部值,无论以后更改A(如上面的原始指针示例)?

1 个答案:

答案 0 :(得分:3)

如果你做同样的事情,他们的行为方式相同

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