C++智能指针之auto_ptr
Deprecated in C++ 11,因为Transfer of ownership。比如作为函数参数传递时,会丧失所有权。
- get() 获取原始指针
- release() 释放auto_ptr并返回原始指针
- reset(X*) 释放对象并为auto_ptr设置新值
- operator* 解引用对象
- operator-> 解引用对象成员
- operator= 拷贝并转移所有权
#include <memory> struct S { int i; }; int main() { std::auto_ptr<int> p1(new int); *p1.get() = 1; std::auto_ptr<int> p2(p1); // p1 is now null-pointer auto_ptr std::auto_ptr<int> p3 = p2; // p2 is now null-pointer auto_ptr p3.reset(new int); *p3 = 2; int* pi = p3.release(); // p3 is now null-pointer auto_ptr delete pi; std::auto_ptr<S> ps(new S); ps->i = 3; return 0; }