1、scoped_array

是专门对数组空间进行管理的。包装了new[]在堆上分配的动态数组;

scoped_array弥补了标准库中没有指向数组的智能指针的缺憾。

2、此类特点如下:

(1)、构造函数接受的指针p必须是new[]的结果,不能是new;

(2)、没有*、->操作符的重载(库中不提供这些的重载,但是我们可以自己写),因为scoped_array所持有的不是一个普通的指针;

(3)、析构则必须用delete [];

(4)、提供operator[]的重载,可以像普通数组一样进行下标访问元素;

(5)、没有begin()、end()等类似容器的迭代器操作函数;

scoped_array与scoped_ptr有相同的设计思想,也是局部智能指针,不能拷贝和赋值;

3、怎么使用scoped_array

#include<iostream>#include<boost/smart_ptr.hpp>//内部实现好的,直接调用系统的。usingnamespacestd;usingnamespaceboost;//这个命名空间必须要有。intmain(void){int*p=newint[10];//申请数组空间scoped_array<int>ps(p);//交与智能指针管理for(inti=0;i<10;i++){ps[i]=i+1;//可以进行下标操作}for(i=0;i<10;i++){cout<<ps[i]<<"";}cout<<endl;}//拷贝构造和赋值都不可以。

4、scoped_array源码的实现

#include<iostream>usingnamespacestd;template<classT>classscoped_array{public:explicitscoped_array(T*p=0):px(p){}//预防隐式调用~scoped_array(){delete[]px;}public:typedefscoped_array<T>this_type;voidreset(T*p=0){//重置方法this_type.swap(*this);//无名临时对象}voidswap(scoped_array&b){T*tmp=b.px;b.px=px;px=tmp;}T*get()const{returnpx;}T&operator[](inti)const{//下标越界没有检测//return*(px+i);returnpx[i];}T&operator*()const{returnpx[0];}T*operator+(inti)const{returnpx+i;}private:T*px;scoped_array(scoped_arrayconst&);//放到私有中,外界无法调用scoped_array&operator=(scoped_arrayconst&);voidoperator==(scoped_arrayconst&)const;voidoperator!=(scoped_arrayconst&)const;};intmain(void){int*p=newint[10];scoped_array<int>ps(p);*ps=2;for(inti=0;i<10;i++){ps[i]=i+1;}*(ps+3)=100;//利用+,*的运算符的重载即可以实现。for(i=0;i<10;i++){cout<<ps[i]<<"";}cout<<endl;}

库中没有提供*和+的重载。

scoped_array缺点:

不能动态增长,没有迭代器支持,不能搭配STL算法,是纯粹的裸接口,不推荐使用。