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