关于auto_ptr :: reset的问题

时间:2010-07-17 18:49:43

标签: c++ pointers smart-pointers auto-ptr

请任何人解释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;
}

2 个答案:

答案 0 :(得分:5)

auto_ptr管理指针。 reset将删除它所拥有的指针,并指向其他内容。

所以你从auto_ptr p开始,指向什么都没有。当您reset使用new int时,它会删除任何内容,然后指向动态分配的int。然后,您为int分配5。

然后再次reset,删除先前分配的int,然后指向新分配的int。然后,您将10分配给新的int

当函数返回时,auto_ptr超出范围并调用其析构函数,删除最后分配的int并且程序结束。

答案 1 :(得分:2)

也许这个例子会更好:

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)

重要的一行是新指针传递给reset方法的地方。在输出中,您可以看到tester的构造函数被调用,然后指针被传递给reset方法,自动指针处理先前管理的内存并删除显示{{1}的对象在输出中。同样,在函数结束时,自动指针超出范围,它会处理存储的指针打印~tester(1)

相关问题