boost学习scoped_ptr,shared_ptr

#include <boost/smart_ptr.hpp>
#include <string>
#include <iostream>
//#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;

struct posix_file
{
    posix_file(const string& filename)
    {
           cout <<"open file" << filename << endl;
    }
    ~posix_file()
    {
            cout << "close file" << endl;
    }
};


class shared_ptr_tese
{
    private:
        shared_ptr<int> sp;
    public:
        shared_ptr_tese(shared_ptr<int> _sp):sp(_sp){}
        void print()
        {
               cout << "count:  " << sp.use_count() <<  "\tv:   " << *sp<< endl;
        }
};

void print(shared_ptr<int> p)
{
      cout << "count:  " << p.use_count() <<  "\tv:   " << *p<< endl;
}

//smart pointer test
int main(int argc, char** argv)
{
    //scoped_ptr, 不需要delete,内存自动释放
    //scoped 不允许拷贝,不允许赋值,因为这都是私有的,所以也不能用于容器
    scoped_ptr<string> sp(new string("this is test"));
    cout << *sp << endl;
    cout << sp->size()<< endl;

    scoped_ptr<int> p(new int);
    if(p)
    {
        *p=10;
        cout<< *p << endl;
    }
    p.reset();
    assert(p==0);
    //结束时自动调用析构函数
    scoped_ptr<posix_file> pfile(new posix_file("a.txt"));
    //auto_ptr拥有指针的转移权
    auto_ptr<int> ap(new int(10));
    scoped_ptr<int> sp1(ap);
    //scoped_ptr<int> sp1(sp1); 指针的所以权不能转移

    assert(ap.get() == 0); //ap不再拥有指针
    ap.reset(new int(20));
    cout << "*ap" << *ap << "\t" << "*sp1" << *sp1 << endl;

    //scoped_array,不过不推荐使用,因为这部分工作都可以使用vector来代替
    int *arr=new int[100];
    scoped_array<int> sa(arr);
    for(int i=0;i<100;i++)
    {
        sa[i] = i; //sa+i is error
    }

    //shared_ptr
    shared_ptr<int> shp(new int(20));
    assert(shp.unique()); //现在是唯一的拥有者
    shared_ptr<int> shp1(shp);
    assert(shp.unique() == false);
    assert(shp==shp1 && shp.use_count() == 2);//指向同一个对象,引用计数现在为2了

    *shp1=50;//解引用
    assert(*shp =- 50);//另外一个也跟着改变

    //使用类来测试
    shared_ptr<int> sp0(new int(300));
    shared_ptr_tese spt1(sp0); 
    shared_ptr_tese spt2(sp0);
    spt1.print();//count:  3       v:   300
    spt2.print();//count:  3       v:   300

    *sp0 = 3000;
    //因为传递的不是引用,所以引用值又加1
    spt1.print();//count:  3       v:   3000 
    print(sp0);  //count:  4       v:   3000


    //传入的定制删除器
    shared_ptr<FILE> fp(fopen("a.txt","r"), fclose);

    //shared_array
    int *p1 = new int[100];
    shared_array<int> psa(p1); //代理数组
    shared_array<int> psa1(psa); //引用计数增加

    psa[0] = 10; //使用[]访问数组
    assert(psa[0] == 10);
    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值