关于 auto_ptr::reset 的问题
请任何人解释一下来自 C++ 参考站点的这段代码:
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
auto_ptr
管理指针。reset
将删除它所拥有的指针,并指向其他内容。所以你从
auto_ptr p
开始,指向任何东西。当您使用new int
重置
时,它不会删除任何内容,然后指向动态分配的int
。然后将 5 分配给该int
。然后再次
重置
,删除之前分配的int
,然后指向新分配的int
。然后将 10 分配给新的int
。当函数返回时,
auto_ptr
超出范围并调用其析构函数,该析构函数将删除最后分配的int
并且程序结束。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 youreset
withnew int
, it deletes nothing and then points to a dynamically allocatedint
. You then assign 5 to thatint
.Then you
reset
again, deleting that previously allocatedint
and then point to a newly allocatedint
. You then assign 10 to the newint
.When the function returns,
auto_ptr
goes out of scope and has its destructor called, which deletes the last allocatedint
and the program ends.也许这个例子会更好:
重要的一行是将新指针传递给重置方法的地方。在输出中,您可以看到调用了
tester
的构造函数,然后将指针传递给reset
方法,自动指针处理先前管理的内存并删除在输出中显示~tester(1)
的对象。类似地,在函数末尾,自动指针超出范围时,它会处理存储的指针打印~test(2)
Maybe the example would be better as:
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 thereset
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)