c++智慧指標學習
阿新 • • 發佈:2018-12-17
1.標頭檔案:
#include<memory>
2.要領:
注意我們訪問auto_ptr的成員函式時用的是“.”
3. auto prt
?c++呼叫getxxx()方法返回引用,是否破壞了安全性
#include <iostream> #include <memory> using namespace std; class Test { public: Test(string s){ str = s; cout << "test create\n"; } ~Test(){ cout << "Test delete:" << str << endl; } string& getStr(){ return str; } void setStr(string s){ str = s; } void print(){ cout << str << endl; } private: string str; }; int main(int argc, char *argv[]) { auto_ptr<Test> ptest(new Test("123")); ptest->setStr("hello"); ptest->print(); ptest.get()->print(); //return a reference is not safe ptest->getStr()+="world!"; (*ptest).print(); ptest.reset(new Test("123")); ptest->print(); return 0; } ~