c++ stl auto_ptr智能指针

来源:互联网 发布:淘宝技术模式分析 编辑:程序博客网 时间:2024/05/18 02:30
C++的auto_ptr所做的事情,就是动态分配对象以及当对象不再需要时自动执行清理。

auto_ptr在构造时获取对某个对象的所有权(ownership),在析构时释放该对象。我们可以这样使用auto_ptr来提高代码安全性:
int* p = new int(0);auto_ptr<int> ap(p);
从此我们不必关心应该何时释放p,也不用担心发生异常会有内存泄漏。

这里我们有几点要注意:
1) 因为auto_ptr析构的时候肯定会删除他所拥有的那个对象,所有我们就要注意了,一个萝卜一个坑,两个auto_ptr不能同时拥有同一个对象。像这样:
int* p = new int(0);auto_ptr<int> ap1(p);auto_ptr<int> ap2(p);

2) 考虑下面这种用法:
int* pa = new int[10];auto_ptr<int> ap(pa);
因为auto_ptr的析构函数中删除指针用的是delete,而不是delete [],所以我们不应该用auto_ptr来管理一个数组指针

用法:
#include "stdafx.h"#include <iostream>#include <memory>using std::cout;using std::endl;using std::auto_ptr;class WebSite{public:WebSite(){cout << "WebSite" << endl;}~WebSite(){cout << "~WebSite" << endl;}};void f(int nId){WebSite *pJieSoon = new WebSite;auto_ptr<WebSite> pautoWebSite(pJieSoon);if(nId > 0){cout << "nId > 0" << endl;}else if(nId < 0){cout << "nId < 0" << endl;}else{return;}delete pJieSoon;}int _tmain(int argc, _TCHAR* argv[]){f(0);getchar();return 0;}