1:为什么出现智能指针
为了避免多个指针指向一个对象的时候 销毁其中一个point 其他的point就会变成空point 或者多次删除被指向对象而发生报错
或者单纯删除指针 不删除其指向的对象 当最后一个指向对象被删除的时候 对象依然存在 造成资源泄露
智能指针就是为了解决上述问题而存在的
2:智能指针的类型
智能指针有两大类型(C++11的语法)
Class shared_ptr多个智能指针可以指向同一个对象 当最后一个智能指针被销毁的时候 该对象和相关资源会被释放
unique_ptr实现独占或者严格拥有的概念 保证同一时间内只有一个指针指向其对象,可以移交拥有权 对于因为new而创建的对象因为发生异常而忘记 调用delete很有用
注意:auto_ptr是为了辅助unique_ptr而存在的指针 不容易理解且容易出错 C++11不推荐使用 除非还有旧的代码需要维护
所有的smart指针都被定义在中
3:智能指针的使用
shared_ptr一般不用担心资源的释放
#include<iostream>
#include<string>
#include<vector>
#include<memory>
using namespace std;
int main()
{
//shared_ptr<string> PNico(new string("nico"));
std::shared_ptr<string> PNico(new string("nico"), [](string* p) {
cout << " delete : " << *p << endl;
delete p;
});
std::shared_ptr<string> PJutta(new string("jutta"));
(*PNico)[0] = 'N';
PJutta->replace(0, 1, "J");
//把这两个智能指针多次插入对象中
vector<shared_ptr<string>> Coffee;
Coffee.push_back(PJutta);
Coffee.push_back(PJutta);
Coffee.push_back(PNico);
Coffee.push_back(PJutta);
Coffee.push_back(PNico);
for (auto ptr : Coffee)
{
cout << *ptr<<" ";
}
cout << endl;
//通过指针重写对象
//*PNico = "Nicolai";
for (auto ptr : Coffee)
{
cout << *ptr << " ";
}
cout << endl;
//指向这两个对象的分别有4 个 3 个
cout << "use_count:" << Coffee[0].use_count() << endl;
cout << "use_count:" << Coffee[2].use_count() << endl;
//定义一个Deleter shared构造参数
//在这里PNico指向的对象都为空了 自动调用销毁函数 销毁对象 resize之后
PNico = nullptr;
Coffee.resize(2);
//注意在return 0后也会自动销毁对象
return 0;
}
4:对于array
shared_ptr提供的default delete调用的delete 不是delete[] 当share_ptr有“由new创建的单一对象的时候"default delete才会生效
可以自定义deleter对于array
std::shared_ptr<int> p(new int[10],[](int * p)
{
delete []p;
});
//使用unique_ptr提供的辅助函数 内调delete[]
std::shared_ptr<int> p(new int[10],std::default_delete<int[]>());
注意:shared_ptr不提供operator[]
unique_ptr提供
5:shared_ptr易错点
需要确保某对象只被一组shared_ptr指针拥有
下面代码是错的
int * p=new int;
share_ptr sp1§;
share_ptrsp2§;
sp1 和sp2都有权限去释放资源 可能资源会被释放 避免方式就是
在创建对象的时候设立smart point
shared_ptr sp1(new int);
shared_ptr sp2(sp1); //ok