Search code examples
c++pointerssmart-pointersauto-ptr

question about auto_ptr::reset


please can anybody explain this code from C++ Reference site:

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

int main () {
  auto_ptr<int> p;

  p.reset (new int);
  *p=5;
  cout << *p << endl;

  p.reset (new int);
  *p=10;
  cout << *p << endl;

  return 0;
}

Solution

  • auto_ptr manages a pointer. reset will delete the pointer it has, and point to something else.

    So you start with auto_ptr p, pointing to nothing. When you reset with new int, it deletes nothing and then points to a dynamically allocated int. You then assign 5 to that int.

    Then you reset again, deleting that previously allocated int and then point to a newly allocated int. You then assign 10 to the new int.

    When the function returns, auto_ptr goes out of scope and has its destructor called, which deletes the last allocated int and the program ends.