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

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类似,赋值运算符被声明为私有。 ->改为用。标识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值