c++11 stl 学习之 shared_ptr
shared_ptr
智能指针 shared_ptr 的声明初始化方式
由于指针指针使用explicit参数 必须显示声明初始化
shared_ptr<string> pNico = new string("nico"); // ERROR
shared_ptr<string> pNico{new string("nico")}; // OK
也可以使用make_shared()
shared_ptr<string> pNico = make_shared<string>("nico");
shared_ptr<string> pJutta = make_shared<string>("jutta");
智能指针一旦声明
就不能再次分配 除非使用reset()
shared_ptr<string> pNico4;
pNico4 = new string("nico");
//ERROR: no assignment for ordinary pointers
pNico4.reset(new string("nico")); // OK
shared_ptr的使用方式与实际指针使用类似 基本没什么区别
示例 sharedPtrTest1()
//=======================================
对于shared_ptr中的参数 可以指定 删除器 Deleter
示例 sharedPtrTest2()
#include <iostream> #include <string> #include <vector> #include <memory> #include <fstream> //for ofstream #include <cstdio> //for remove() using namespace std; void sharedPtrTest1() { 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(pJutta); whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pNico); whoMadeCoffee.push_back(pJutta); whoMadeCoffee.push_back(pNico); for (auto ptr : whoMadeCoffee) { cout << *ptr << " "; } cout << endl; // overwrite a name again *pNico = "Nicolai"; // print all elements again for (auto ptr : whoMadeCoffee) { cout << *ptr << " "; } cout << endl; // print some internal data cout << "use_count: " << whoMadeCoffee[0].use_count() << endl; } class FileDeleter { private: std::string filename; public: FileDeleter(const std::string& fn) : filename(fn) { } void operator () (std::ofstream* fp) { fp->close(); //close.file std::remove(filename.c_str()); //delete file cout << "delete file finish" << endl; } }; void sharedPtrTest2() { shared_ptr<std::ofstream> fp(new std::ofstream("tmpfile.txt"), FileDeleter("tmpfile.txt")); } int _tmain(int argc, _TCHAR* argv[]) { sharedPtrTest1(); sharedPtrTest2(); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。