c++智能指针:boost::scoped_ptr,boost::shared_ptr,boost::scoped_array

来源:互联网 发布:美工课教案 编辑:程序博客网 时间:2024/05/29 05:56

boost::scoped_ptr使用示例:

#include <iostream>#include <string>#include <boost/smart_ptr.hpp>using namespace std;class TestBody{public:    TestBody(int param = 0):m_num(param)    {        m_info = "INFO";        cout<<"construct TestBody"<<endl;    }    ~TestBody()    {        cout<<"destory TestBody"<<endl;    }    void SetInfo(string info)    {        m_info = info;    }    void PrintInfo()    {        cout<<"info:"<<m_info<<endl;    }private:    int m_num;    string m_info;};void TestBoostScopedPtr(){    boost::scoped_ptr<TestBody> smartPoint1(new TestBody(1));    if(smartPoint1.get())    {        smartPoint1->PrintInfo();        smartPoint1->SetInfo("TestBoostScopedPtr");        smartPoint1->PrintInfo();    }}int main(void){    TestBoostScopedPtr();    return 0;}

运行结果:
这里写图片描述

如果增加赋值语句,则会提示编译错误。

void TestBoostScopedPtr(){    boost::scoped_ptr<TestBody> smartPoint1(new TestBody(1));    if(smartPoint1.get())    {        smartPoint1->PrintInfo();        smartPoint1->SetInfo("TestBoostScopedPtr");        smartPoint1->PrintInfo();        boost::scoped_ptr<TestBody> smartPoint2;        smartPoint2 = smartPoint1; //编译错误    }}

查看源码实现,发现赋值语句声明为private

template<class T> class scoped_ptr // noncopyable{private:    T * px;    scoped_ptr(scoped_ptr const &);    scoped_ptr & operator=(scoped_ptr const &);    typedef scoped_ptr<T> this_type;    void operator==( scoped_ptr const& ) const;    void operator!=( scoped_ptr const& ) const;public:}

boost::shared_ptr使用示例:

void TestBoostSharedPtr(){    boost::shared_ptr<TestBody> smartPoint1(new TestBody(1));    if(smartPoint1.get())    {        smartPoint1->PrintInfo();        smartPoint1->SetInfo("TestBoostSharedPtr");        cout<<"use_count Point1:"<<smartPoint1.use_count()<<endl;        boost::shared_ptr<TestBody> smartPoint2;        smartPoint2 = smartPoint1;        smartPoint2->PrintInfo();        smartPoint1->PrintInfo();        cout<<"use_count  Point1:"<<smartPoint1.use_count()<<endl;        cout<<"use_count  Point2:"<<smartPoint2.use_count()<<endl;    }    cout<<"use_count  Point1:"<<smartPoint1.use_count()<<endl;}

执行结果:
这里写图片描述

boost::scoped_array使用示例:

void TestBoostScopedArray(){    boost::scoped_array<TestBody> smartPoint(new TestBody[3]);    if(smartPoint.get())    {        smartPoint[0].PrintInfo();        smartPoint[1].PrintInfo();        smartPoint[2].PrintInfo();        smartPoint[0].SetInfo("TestBoostSharedPtr0");        smartPoint[1].SetInfo("TestBoostSharedPtr1");        smartPoint[0].PrintInfo();        smartPoint[1].PrintInfo();    }}

运行结果:
这里写图片描述

和scoped_ptr类似,赋值运算符被声明为私有。 ->改为用。标识。

0 0