C++中的auto_ptr智能指针的作用及使用方法详解

2020-01-06 15:30:09于海丽

智能指针(auto_ptr) 这个名字听起来很酷是不是?其实auto_ptr 只是C++标准库提供的一个类模板,它与传统的new/delete控制内存相比有一定优势,但也有其局限。本文总结的8个问题足以涵盖auto_ptr的大部分内容。

 auto_ptr是什么?

auto_ptr 是C++标准库提供的类模板,auto_ptr对象通过初始化指向由new创建的动态内存,它是这块内存的拥有者,一块内存不能同时被分给两个拥有者。当auto_ptr对象生命周期结束时,其析构函数会将auto_ptr对象拥有的动态内存自动释放。即使发生异常,通过异常的栈展开过程也能将动态内存释放。auto_ptr不支持new 数组。

该类型在头文件memory中,在程序的开通通过 #include<memory> 导入,接下来讲解该智能指针的作用和使用。

使用方法:

  auto_ptr<type> ptr(new type()); 这是该指针的定义形式,其中 type 是指针指向的类型,ptr 是该指针的名称。

  比如该type 是int,具体定义如下:

  auto_ptr<int> ptr(new int(4));

  比如该type 是map<int,vector<int> >,具体定义如下:

  auto_ptr<map<int,vector<int> > > ptr(new map<int,vector<int> > ());

  当然可以先定义,后赋值,如下所示:

  auto_ptr<map<int,int> > ptr;
  ptr = auto_ptr<map<int,int> >(new map<int,int> ());

作用1:保证一个对象在某个时间只能被一个该种类型的智能指针所指向,就是通常所说的对象所有权。

作用2:对指向的对象自动释放的作用,详情看如下代码。

代码片段一:


#include <iostream>
#include <string.h>
#include <memory>
#include <string>
#include <Windows.h>
#include <map>
#include <ctime>
#include <vector>
using namespace std;#define MAXN 20000000
class test_ptr
{
public:
map<int,int> *p;
test_ptr()
{
p = new map<int,int>();
for(int i = 0;i<MAXN;i++)
p->insert(make_pair(i,i));
}
};
int main(int argc,char *argv[])
{
for(int i = 0;i<100;i++)
{
Sleep(1000);
cout << i << endl; // 输出 创建次数
test_ptr * tmp = new test_ptr();
}
system("pause");
return 0;
} 

 

在某些情况下,可能我们就会写出上面的代码来,通过运行会发现存在内存溢出。对于一些经验老道的程序员可能会作如下改写:

代码片段二:


#include <iostream>
#include <string.h>
#include <memory>
#include <string>
#include <Windows.h>
#include <map>
#include <ctime>
#include <vector>
using namespace std;
#define MAXN 20000000
class test_ptr
{
public:
map<int,int> *p;
test_ptr()
{
//p = auto_ptr<map<int,int> > (new map<int,int>());
p = new map<int,int>();
for(int i = 0;i<MAXN;i++)
p->insert(make_pair(i,i));
}
~test_ptr()
{
delete p;
}
};
int main(int argc,char *argv[])
{
for(int i = 0;i<100;i++)
{
Sleep(1000);
cout << i << endl; 
test_ptr * tmp = new test_ptr();
}
system("pause");
return 0;
}