#include <memory>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void main()
{
shared_ptr<string>pNico(new string("Nico"));
shared_ptr<string>pJutta(new string("Jutto"));
//shared_ptr 's ctor is explicit,so "=" ==> ctor is impossible
//replace & reset
vector<shared_ptr<string>>vPNJ;
vPBJ.push_back(pJutta);
vPBJ.push_back(pJutta);
vPBJ.push_back(pNico);
vPBJ.push_back(pJutta);
vPBJ.push_back(pNico);
cout << "use_count:" << VPBJ[0].use_count() << endl;//4
//because push_back copying of raw_shared_ptr, so, 4 = 3+1
shared_ptr<string>pNico(new string("Nico"), [](string *p){
cout << "delete" << *p << endl;
});
//这个P应该理解,调用~(),的原因,就应该是new 的 p 绑定的 delete
//to array[]
//没有默认的 dtor[],只能自定义
//使用 unique_ptr的helper
shared_ptr<string>pNico(new int[10],std::default_delete<int[]>());
shared_ptr<string>pNico(new int[10],[](int*p){
delete[] p;
});
//but unique_ptr 不一样
//必须提供dtor的模板参数
unique_ptr<int, void(*)(int*)>p(new int[10],[](int*p){
delete[] p;
})
}
shared和unique的基础用法
猜你喜欢
转载自blog.csdn.net/qq_24328911/article/details/51405954
今日推荐
周排行