c++ 智能指针的使用
https://www.cnblogs.com/TenosDoIt/p/3456704.html
#include <QCoreApplication> #include <string> #include <iostream> #include <memory> using namespace std; class Test { public: Test(string s) { str = s; cout<<"Test creat : " << str << endl; } ~Test() { cout<<"Test delete:"<<str<<endl; } string& getStr() { return str; } void setStr(string s) { str = s; } void print() { cout<<str<<endl; } private: string str; }; unique_ptr<Test> fun() { return unique_ptr<Test>(new Test("789")); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); auto_ptr<Test> ptest0(new Test("123")); ptest0->setStr("hello "); ptest0->print(); ptest0.get()->print(); ptest0->getStr() += "world !"; (*ptest0).print(); ptest0.reset(new Test("123")); ptest0->print(); cout << "\n"; unique_ptr<Test> ptest1(new Test("123")); unique_ptr<Test> ptest2(new Test("456")); ptest1->print(); ptest2 = std::move(ptest1);//不能直接ptest2 = ptest1 if(ptest1 == NULL)cout<<"ptest = NULL\n"; Test* p = ptest2.release(); p->print(); ptest1.reset(p); ptest1->print(); ptest2 = fun(); //这里可以用=,因为使用了移动构造函数 ptest2->print(); cout << "\n"; shared_ptr<Test> ptest(new Test("123")); shared_ptr<Test> ptest23(new Test("456")); cout<<ptest23->getStr()<<endl; cout<<ptest23.use_count()<<endl; ptest = ptest23;//"456"引用次数加1,“123”销毁 ptest->print(); cout<<ptest23.use_count()<<endl;//2 cout<<ptest.use_count()<<endl;//2 ptest.reset(); ptest23.reset();//此时“456”销毁 cout<<"done !\n"; return a.exec(); }