Demonstrate an auto_ptr : auto_ptr « Pointer « C++ Tutorial






#include <iostream>
#include <memory>
using namespace std;

class MyClass {
public:
  MyClass() {
     cout << "constructing\n";
  }
  ~MyClass() {
     cout << "destructing\n";
  }
  void f() {
     cout << "f()\n";
  }
};

int main()
{
  auto_ptr<MyClass> p1(new MyClass), p2;

  p2 = p1; // transfer ownership
  p2->f();

  // can assign to a normal pointer
  MyClass *ptr = p2.get();
  ptr->f();

  return 0;
}
constructing
f()
f()
destructing








11.5.auto_ptr
11.5.1.Demonstrate an auto_ptr
11.5.2.Define output operator for auto_ptr print object value or NULL
11.5.3.const auto_ptr
11.5.4.class auto_ptr: improved standard conforming implementation