开发者

question about auto_ptr::reset

pl开发者_如何学Pythonease 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_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.


Maybe the example would be better as:

struct tester {
   int value;
   tester(int value) : value(value) 
   { std::cout << "tester(" << value << ")" << std::endl; }
   ~tester() { std::cout << "~tester(" << value << ")" << std::endl; }
};
int main() {
   std::auto_ptr<tester> p( new tester(1) ); // tester(1)
   std::cout << "..." << std::endl;
   p.reset( new tester(2) );                 // tester(2) followed by ~tester(1)
   std::cout << "..." << std::endl;
}                                         // ~tester(2)

The important line being where a new pointer is passed to the reset method. In the output you can see that the constructor of tester is called and then the pointer is passed to the reset method, the auto pointer takes care of the previously managed memory and deletes the object showing ~tester(1) in the output. Similarly, at the end of the function, where the auto pointer goes out of scope, it takes care of the stored pointer printing ~test(2)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜