您的位置:首页 > 编程语言 > C语言/C++

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

2015-12-15 14:42 549 查看
boost::scoped_ptr使用示例:

[code]#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;
}


运行结果:



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

[code]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

[code]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使用示例:

[code]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使用示例:

[code]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类似,赋值运算符被声明为私有。 ->改为用。标识。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: