场景:
1.在函数里如果使用了外边传进去的类对象指针,如果这些对象需要在函数完成调用时自动销毁,这时候可以使用auto_ptr.帮你管理类对象指针的生命周期。
2.auto_ptr只在同一个函数里使用,不要传递.
#include <iostream>
#include <string>
#include <memory>
using std::cout;
using std::endl;
class A
{
public:
A()
{
cout << "A" << endl;
}
~A()
{
cout << "~A" << endl;
}
int i_;
};
int main(int argc, char *argv[])
{
cout << "begin" << endl;
A* a = new A();
cout << "a is: " << a << endl;
std::auto_ptr<A> a_auto(a);
std::auto_ptr<A> a_auto2 = a_auto;//传递了owner,会导致无法分清owner最终指向谁.禁用.
std::auto_ptr<A> a_auto3(a);//指向同一个指针,禁用.这样会连续调用两次析构.
//auto_ptr只在一个函数里使用,不要在函数参数里使用.
cout << "a_auto is: " << a_auto.get() << endl;
cout << "a_auto2 is: " << a_auto2.get() << endl;
cout << "endl" << endl;
return 0;
}
输出:
begin
A
a is: 0x2f1000
a_auto is: 0
a_auto2 is: 0x2f1000
endl
~A
~A