Skip to content

Instantly share code, notes, and snippets.

@s-shin
Created October 14, 2016 03:56
Show Gist options
  • Save s-shin/a1f7293cd0c104ba3ac1b35cce178fdd to your computer and use it in GitHub Desktop.
Save s-shin/a1f7293cd0c104ba3ac1b35cce178fdd to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
std::shared_ptr<int*> CreatePointerNG(int v) {
auto foo = std::make_shared<int>(v);
return std::make_shared<int*>(foo.get());
}
std::shared_ptr<int*> CreatePointerOK(int v) {
auto foo = std::make_shared<int>(v);
std::shared_ptr<int*> p(foo, new int*(foo.get()));
return p;
}
int main() {
auto p1 = CreatePointerNG(100);
std::cout << "p1: " << *p1 << " " << **p1 << std::endl;
auto p2 = CreatePointerOK(200);
std::cout << "p2: " << *p2 << " " << **p2 << std::endl; // p1 is deleted
std::cout << "p1: " << *p1 << " " << **p1 << std::endl; // then reused
auto p3 = CreatePointerOK(300);
std::cout << "p3: " << *p3 << " " << **p3 << std::endl; // p2 is alive
std::cout << "p2: " << *p2 << " " << **p2 << std::endl; // then not reused.
return 0;
}
// p1: 0x7fdf20d00018 100
// p2: 0x7fdf20d00018 200
// p1: 0x7fdf20d00018 200
// p3: 0x7fdf20d00068 300
// p2: 0x7fdf20d00018 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment