boost::scoped_ptr用法

示例代码如下:

#include <iostream> 
#include <boost/smart_ptr.hpp>

class P
{
public:
    P()
    {
        t = 7;
    }

    ~P()
    {
        t = 10;
    }

private:
    int t;
};

class posix_file
{
public:
    posix_file(char* filename)
    {
        std::cout << "open file"<< filename << std::endl;
    }

    ~posix_file()
    {
        std::cout << "close file." << std::endl;
    }
};

int main()
{

    std::auto_ptr<P> p1(new P);
    std::auto_ptr<P> p2;// = new P();
    p2.reset(new P());


    //boost::scoped_ptr类摘要
    /*
    template <class T>
    class scoped_ptr
    {
    private:
        T* px;
        //由于拷贝构造函数和赋值运算符(甚至是全局的!=、==运算符)申明为私有,
        //故该类不能使用这些方法
        scoped_ptr(scoped_ptr const &);
        scoped_ptr& operator=(scoped_ptr const &);

    public:
        scoped_ptr(T* p = 0);
        ~scoped_ptr();

        void reset(T* p = 0);

        T& operator*() const;
        T& operator->() const;
        T* get() const;

        operator unspecified-bool-type() const;
        void swap(scoped_ptr& b);
    };

    */


    boost::scoped_ptr<std::string> p3(new std::string("helloworld!"));
    //可以像普通指针一样解引用
    std::cout << *p3 << std::endl;
    std::cout << p3->size() << std::endl;
    //以下代码非法:不允许对p3进行指针算术操作
    // p3++;
    //不允许对p4进行拷贝构造
    //boost::scoped_ptr<std::string> p4 = p3;

    //可以对p3进行bool语境测试
    if (p3)
    {
        //do something
    }

    //reset方法仅仅是为了演示,不推荐这么用。
    p3.reset();
    assert(p3 == NULL);

    //文件类在离开作用域之后会自动释放文件资源
    boost::scoped_ptr<posix_file> pfile(new posix_file("test.txt"));

    return 0;
}

boost::scoped_ptr与std::auto_ptr的区别是:前者的设计意图是指针语义不可以转移的,根本原因是其拷贝构造函数和赋值运算符被设置为私有;而后者的指针语义是可以转移的(注意:在传递过程中要特别小心,以免出错)。示例如下:

#include <iostream> 
#include <boost/smart_ptr.hpp>
int main()
{
    std::auto_ptr<int> ap(new int(10));
    boost::scoped_ptr<int> sp(ap);          
    assert(ap.get() == 0);                  //ap不再拥有指针

    ap.reset(new int(20));
    std::cout << *sp << ", " << *ap << std::endl;

    std::auto_ptr<int> ap2;
    ap2 = ap;                       //ap2从ap处获得指针所有权
    assert(ap.get() == 0);          //ap不再拥有指针

    boost::scoped_ptr<int> sp2;
    //赋值操作无法编译通过
    sp2 = sp;

    return 0;
}

std::auto_ptr和boost::scoped_ptr对象均不能作为容器的元素,因为不满足stl对元素的要求,具体细节见:
http://www.cppblog.com/happem/archive/2012/08/27/188415.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值