一.智能指针
1.引入
我们通常使用类似new申请一块空间,交由一个指针指向,假如说最后忘记delete,将会造成内存泄露。而智能指针的出现,就是对这种问题的解决方式,智能指针类似指针,却可以用于管理动态分配的内存。本章所解说的是三种智能指针:
(1)C++98提出,C++11摒弃的auto_ptr
C++11新增的
(2)shared_ptr
(3)unique_ptr
在C++里面,三者都被以模板的形式实现,下面是对智能指针的使用提示:
(1)智能指针的头文件是#include<memory>
(2)由于unique_ptr和shared_ptr是C++11新增的智能指针,所以编译时需要添加支持C++11的参数
如g++ xx.cpp -o xx -std=c++11
(3)智能指针在std域里,需要添加名称空间using namespace std
,或者在智能指针前加std::
//test1
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Report
{
public:
Report(const std::string s):str(s)
{
cout<<"Object created"<<endl;
}
~Report()
{
cout<<"Object deleted"<<endl;
}
void comment()const
{
cout<<str<<endl;
}
private:
std::string str;
};
int main(int argc, char* const argv[])
{
//test1: use smart ptr
{
std::auto_ptr<Report> ps(new Report("using auto_ptr"));
ps->comment();
}
{
std::shared_ptr<Report> ps(new Report("using shared_ptr"));
ps->comment();
}
{
std::unique_ptr<Report> ps(new Report("using unique_ptr"));
ps->comment();
}
return 0;
}
执行结果
[root@server10 auto_ptr]# ./t
Object created
using auto_ptr
Object deleted
Object created
using shared_ptr