学习笔记三:boost智能指针:scoped_ptr和shared_ptr

1.scoped_ptr所管理的指针,所有权不能被转让。scoped_ptr的拷贝构造函数和赋值操作符都声明为了私有,这样scoped_ptr不能进行复制操作,其所含指针就不能改变所有权。
2.提供了*和->操作符的重载,这样操作scoped_ptr对象可以像操作原始指针一样方便,但不能进行比较、自增、自减等操作。
3.因为scoped_ptr不支持拷贝和赋值操作,所以scoped_ptr不能作为STL容器的元素。

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace boost;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
     // 1.用法,在构造的时候,接受new表达式结果
     scoped_ptr<string> sp(new string("Test scope ptr"));

    // 2.模拟指针的操作
    cout<<sp->size()<<endl;
    cout<<*sp<<endl;

    // 3.不能进行比较、自增、自减,转移指针等操作
    // ++sp;  // 错误
    // scoped_ptr<string> sp1 = sp; 构造函数为私有函数

    // 4.不能作为stl容器的元素
    // vector<scoped_ptr<string> > vecSP; // 可以通过
    // vecSP.pop_back(sp);                // 错误,因为scoped_ptr不支持拷贝和赋值

    // 5.不能转移所管理的指针的所有权
    auto_ptr<string> ap(new string("Test auto ptr"));
    scoped_ptr<string> sp2(ap);
    assert(ap.get()==0);
    ap.reset(new string("new test"));
    cout<<*sp2<<endl<<*ap<<endl;

    return 0;
}

4.与scoped_ptr不同,shared_ptr可以作为STL容器的元素。(更多shared_ptr的知识之后再了解)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值