Listing 5

#include <memory>
#include <iostream>
using std::auto_ptr; using std::cout;

struct resource
  { // trace resource allocation and release
  resource()
    { // report allocation
    cout << "resource allocated at " << (void*)this << '\n';
    }
  ~resource()
    { // report release
    cout << "resource released at " << (void*)this << '\n';
    }
  void do_something() const {}
  };
typedef auto_ptr<resource> ptr;
void show(const char *title, const ptr& p)
  { // show pointer value
  cout << title << ", resource pointer is " << (void*)p.get() << '\n';
  }
void function(auto_ptr<resource> p)
  { // simple function taking auto_ptr object
  show("in function", p);
  }
int main()
  { // demonstrate transfer of ownership
  auto_ptr<resource> p(new resource);
  show("before function", p);
  function(p);
  show("after function", p);
  return 0;
  }