c++ - Why does std::shared_ptr not behave like raw point when assign to another? -


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

output: *foo: 10 *bar: 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; } 

output: *foo: 20 *bar: 20

how make shared_pt b shared_pt b has same inner value whatever change later (like above raw pointer example) ?

they behave same way if same thing

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

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -