fork download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. template <class T>
  6. inline void out(const T& t) { cout << t << endl; }
  7. inline void out(const char* str) { cout << str << endl; }
  8. template <class T>
  9. inline void out(const char* str, const T& t)
  10. { cout << str << ' ' << t << endl; }
  11.  
  12. class Obj
  13. {
  14. private:
  15. static int count;
  16. int num;
  17. public:
  18. Obj() : num(count++) { out("new", num); }
  19. ~Obj() { out("delete", num); }
  20. void o() { out("mynum", num); }
  21. };
  22. int Obj::count = 0;
  23.  
  24. void foo(auto_ptr<Obj> f) {
  25. out("in foo(auto_ptr):", f.get());
  26. }
  27. void foo(shared_ptr<Obj> f) {
  28. out("in foo(shared_ptr):", f.get());
  29. }
  30. void foo(unique_ptr<Obj> f) {
  31. out("in foo(unique_ptr):", f.get());
  32. }
  33.  
  34. void bar(auto_ptr<Obj>& b) {
  35. out("in bar(auto_ptr):", b.get());
  36. }
  37. void bar(shared_ptr<Obj>& b) {
  38. out("in bar(shared_ptr):", b.get());
  39. }
  40. void bar(unique_ptr<Obj>& b) {
  41. out("in bar(unique_ptr):", b.get());
  42. }
  43.  
  44.  
  45. int main() {
  46. out("start");
  47. auto_ptr<Obj> a(new Obj);
  48. shared_ptr<Obj> s(new Obj);
  49. unique_ptr<Obj> u(new Obj);
  50. out("a:", a.get()); out("s:", s.get()); out("u:", u.get());
  51. foo(a);
  52. foo(s);
  53. foo(move(u)); // foo(u); はエラー
  54. out("a:", a.get()); out("s:", s.get()); out("u:", u.get());
  55. out("reset");
  56. a.reset(new Obj);
  57. s.reset(new Obj);
  58. u.reset(new Obj);
  59. out("a:", a.get()); out("s:", s.get()); out("u:", u.get());
  60. bar(a);
  61. bar(s);
  62. bar(u);
  63. out("a:", a.get()); out("s:", s.get()); out("u:", u.get());
  64. out("finish");
  65. return 0;
  66. }
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
start
new 0
new 1
new 2
a: 0x8811008
s: 0x8811018
u: 0x8811040
in foo(auto_ptr): 0x8811008
delete 0
in foo(shared_ptr): 0x8811018
in foo(unique_ptr): 0x8811040
delete 2
a: 0
s: 0x8811018
u: 0
reset
new 3
new 4
delete 1
new 5
a: 0x8811040
s: 0x8811008
u: 0x8811018
in bar(auto_ptr): 0x8811040
in bar(shared_ptr): 0x8811008
in bar(unique_ptr): 0x8811018
a: 0x8811040
s: 0x8811008
u: 0x8811018
finish
delete 5
delete 4
delete 3