C++智能指针入门

来源:互联网 发布:信托网络个人理财产品 编辑:程序博客网 时间:2024/04/30 17:04

上次,金山面试被问到智能指针,全然不知,静下心来好好学习学习。

C++ 提供四种智能指针auto_ptr, shared_ptr, unique_ptr, week_ptr.

用法:

#include <string>#include <memory>using namespace std;class report{private:    string str;public:    report(const string s):str(s) //构造方法    {        cout<<"1 report Object  has been build!"<<endl;    }    ~report()    {        cout<<"3 report Object  deleted!"<<endl;    }    void talk()    {        cout<<str<<endl;    }};int main(){    string talk="2 hello,this is a test!";    {        auto_ptr<report> ptr(new report(talk));        ptr->talk();    }    {        shared_ptr<report> ptr(new report(talk));        ptr->talk();    }    {        unique_ptr<report> ptr(new report(talk));        ptr->talk();    }    return 0;}






0 0