一、概述
在C语言和C++中,不管我们用C语言的库函数malloc开辟了一块内存,还是用C++的操作符new出了一块内存,我们都要同过free和delete去释放内存。而对于其他高级语言来说,当我们开辟一块内存用完之后,我不用去管这块内存的释放,操作系统默认会帮我们把这块内存释放了。其实这样的机制在C++中也有,只是很少被用到而已,它就是所谓的智能指针。
二、智能指针
1、常规情况
void foo()
{
A* p = new A;
delete p;
}
2、智能指针
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
A()
{
cout << "this is constructor" << endl;
}
~A()
{
cout << "this is destructor" << endl;
}
void dis()
{
cout << "class A`s dis()" << endl;
}
};
int main()
{
//使用智能指针
auto_ptr auto_ptr<A>p(new A);
p->dis();
return 0;
}
这里有必要说明一下,智能指针auto_ptr属于C++98标准的,它能部分第解决资源释放问题。上面这个例子就是说明”自动指针”能够释放资源的案例。auto_ptr 构造函数接受new操作符或者工厂创建出的对象指针作为参数,从而代理了原始指针。虽然它是一个对象,但因为重载了operator*和operator->,其行为类似指针,可以把它用在大多数普通指针可用的地方。当退出作用域时(离开函数main或者发生异常),C++语言会保证auto_ptr对象销毁,调用auto_ptr的析构函数,进而使用delete操作符删除原始指针释放资源。 由于auto_ptr存在一些局限性,故而在C++11/14标准中提供了unique_ptr 、 share_ptr 和 weak_ptr 。除此之外,boost也提供智能指针,在boost.smart_ptr库中,boost提供了六种智能指针,分别是scoped_ptr , scoped_array 、shared_ptr 、share_array 、weak_ptr , intrusive_ptr 。它们是轻量级对象,速度与原始指针相差无几,都是异常安全的(exeception safe),而且对于所有指向的类型T也仅有一个很小的要求:类型T的析构函数不能抛出异常。
3、自定义智能指针
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
A()
{
cout << "this is constructor" << endl;
}
~A()
{
cout << "this is destructor" << endl;
}
void dis()
{
cout << "class A`s dis()" << endl;
}
};
class self_PMA
{
public:
self_PMA(A *p):_p(p){}
~self_PMA()
{
delete p;
}
A& operator*()
{
return *_p;
}
A* operator->()
{
return _p;
}
private:
A* _p;
};
int main()
{
//使用智能指针
self_PMA self_PMA<A>p(new A);
p->dis();
return 0;
}
自定义智能指针重载了operator *和operator->
类名& operator*()
{
函数体
}
类名* operator-‐>()
{
函数体
}
转载请注明原文地址: https://ju.6miu.com/read-4804.html