smart pointer
来源:互联网 发布:电脑监控软件排行 编辑:程序博客网 时间:2024/06/11 09:43
Following examples of book <The C++ Standard Template Library: a Tutorial and Reference>.
#include<iostream>#include<string>#include<vector>#include<memory>using namespace std;int main(){ shared_ptr<string> pNico(new string("nico")); shared_ptr<string> pJutta(new string("jutta")); (*pNico)[0] = 'N'; pJutta->replace(0, 1, "J"); vector<shared_ptr<string>> whoMadeCoffee; whoMadeCoffee.push_back(pNico); whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pNico); auto itr = whoMadeCoffee.begin(); cout << "Before change: " << endl; while(itr!=whoMadeCoffee.end()){ cout << **itr << endl; itr++; } *pNico = "Nicolai"; itr = whoMadeCoffee.begin(); cout << "After change: " << endl; while(itr!=whoMadeCoffee.end()){ cout << **itr << endl; itr++; } cout << "use_cont: " << whoMadeCoffee[0].use_count() << endl; return 0;}
Use user defined destructor.
#include<iostream>#include<string>#include<vector>#include<memory>using namespace std;int main(){ shared_ptr<string> pNico(new string("nico"), [](string* p){cout<<"delete "<<*p<<endl; delete p;}); shared_ptr<string> pJutta(new string("jutta")); (*pNico)[0] = 'N'; pJutta->replace(0, 1, "J"); vector<shared_ptr<string>> whoMadeCoffee; whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pNico); whoMadeCoffee.push_back(pNico); auto itr = whoMadeCoffee.begin(); cout << "Before change: " << endl; while(itr!=whoMadeCoffee.end()){ cout << **itr << endl; itr++; } *pNico = "Nicolai"; itr = whoMadeCoffee.begin(); cout << "After change: " << endl; while(itr!=whoMadeCoffee.end()){ cout << **itr << endl; itr++; } cout << "use_cont: " << whoMadeCoffee[0].use_count() << endl; whoMadeCoffee.resize(2); pNico = nullptr; return 0;}When deal with array, since the default deleter provided by shared_ptr callsdelete, not delete[]. This means that the default deleter is appropriate only if a shared pointer owns a single object created with new. If you use new[] to create an array of objects you have to define your own deleter. You can do that by passing a function, function object, or lambda, which calls delete[ ] for the passed ordinary pointer.
std::shared_ptr<int> p(new int[10], [](int* p){delete[] p;});
0 0
- Smart Pointer
- Smart pointer
- smart pointer
- Smart Pointer
- Smart Pointer
- Smart pointer
- smart pointer
- smart pointer
- smart pointer
- smart pointer
- smart pointer / shared pointer / normal pointer
- Smart Pointer访谈录
- Smart Pointer--智能指针
- Smart Pointer访谈录
- boost smart pointer 笔记
- TR1 smart pointer
- 智能指针(smart pointer)
- smart pointer in gamedev
- 【转载】windows下peersim的安装
- ios 仿android gallery控件
- Linux tar命令详解
- 内存池(MemoryPool)
- C++ 智能指针详解
- smart pointer
- Android apk程序调用其他的APK程序
- 虚继承与虚基类的本质
- http协议的状态码 200、301、304、404、502 HTTP状态码解释
- 项目总结(四)----------Python实现Windows和Linux之间互相传输文件(文件夹)
- 上臣地板南通店荣获“诚信经营示范店”
- Android APK安装包瘦身
- jAVA调优的配置
- Spring3.x中各个jar包的作用总结