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;
}
auto_ptrmanages a pointer.resetwill delete the pointer it has, and point to something else.So you start with
auto_ptr p, pointing to nothing. When youresetwithnew int, it deletes nothing and then points to a dynamically allocatedint. You then assign 5 to thatint.Then you
resetagain, deleting that previously allocatedintand then point to a newly allocatedint. You then assign 10 to the newint.When the function returns,
auto_ptrgoes out of scope and has its destructor called, which deletes the last allocatedintand the program ends.