请任何人都可以从 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;
}
请任何人都可以从 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;
}
auto_ptr
管理一个指针。reset
将删除它拥有的指针,并指向其他东西。
所以你从 开始auto_ptr p
,指向任何东西。当你reset
使用时new int
,它什么都不删除,然后指向一个动态分配的int
. 然后,您将 5 分配给该int
。
然后你reset
再次删除先前分配int
的,然后指向新分配的int
. 然后将 10 分配给新的int
.
当函数返回时,auto_ptr
超出范围并调用其析构函数,该析构函数删除最后分配int
的,程序结束。
也许这个例子会更好:
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
方法,自动指针处理先前管理的内存并删除~tester(1)
输出中显示的对象。同样,在函数结束时,自动指针超出范围,它会处理存储的指针打印~test(2)