auto_ptr

是什么

一个类模板,解决delete发生之前发生异常从而导致内存泄露的问题。

使用时需要包含memory头文件。

void f()
{
	int *ip = new int(42);
	
	...//如果这里发生异常,则下面的delete可能不会执行,导致内存泄露。
	
	delete ip;
}
 
 
 
 
 
#include <iostream>
#include <memory>
using namespace std;

void f()
{
	auto_ptr<int> ap(new int(42));
	//无需delete,发生异常时,超出f的作用域就会释放内存。
}

int main()
{
	return 0;
}

接受指针的构造函数为explicit构造函数,不能使用隐式类型转换。

auto_ptr<int> pi = new int(1024);     //这是错误的。

auto_ptr<int> pi(new int(1024));      //这是正确的。

赋值和复制是破坏性操作

auto_ptr<string> ap1(new string(“hello”));

auto_ptr<string> ap2(ap1);

所有权转移,ap1不再指向任何对象!

 

测试auto_ptr对象是否为空时,要使用get成员。

如auto_ptr<int> p_auto;

//下面错误。

if (p_auto)

    *p_auto = 1024;

 

//下面正确。

if (p_auto.get())

    *p_auto = 1024;

 

不能直接将地址给auto_ptr对象,要使用reset成员。

p_auto = new int(1024);  //error

p_auto.reset(new int(1024));//right

 

auto_ptr只能管理从new返回的指针

int ix = 1024, *p1 = &ix, *p2 = new int(2048);

auto_ptr<int> ap1(p1); //error

auto_ptr<int> ap2(p2); //right

posted @ 2013-05-07 10:08  helloweworld  阅读(174)  评论(0编辑  收藏  举报