shared_array
1、上次写的删除器有些问题:
template<classP,classD>classsp_counted_impl_pd:publicsp_counted_base{public:sp_counted_impl_pd(Pp,Dd):ptr(p),del(d){}public:voiddispose(){del(ptr);//就是这里,将对象用作函数!!!}private:Pptr;Ddel;};
del(ptr) -> del.operator()(ptr);重载了()的类使用起来就是函数对象
删除器:函数对象和函数都可以充当。
2、shared_array
它和shared_ptr类似,它包装了new[]操作符在堆上分配的动态数组,也是采用了引用计数的机制。
shared_array的接口和功能与shared_ptr几乎是相同的,主要区别:
(1)、接受指针p必须是new []的结果
(2)、提供operator[]的重载,可以使用下标
(3)、系统没有提供*、->的重载
(4)、析构函数使用delete [];
3、如何使用shared_array
系统调用:
#include<iostream>#include<boost/smart_ptr.hpp>usingnamespacestd;usingnamespaceboost;intmain(void){int*p=newint[10];shared_array<int>pa(p);//共享数组for(inti=0;i<10;i++){pa[i]=i+1;//系统内进行了[]的重载}for(i=0;i<10;i++){cout<<pa[i]<<"";}cout<<endl;}
4、shared_array
模仿的源码如下:
#ifndef_SHARED_ARRAY_H_#define_SHARED_ARRAY_H_#include"checked_delete.h"template<classT>classshared_array{public:typedefchecked_array_deleter<T>deleter;shared_array(T*p=0):px(p),pn(p,deleter()){}//无名对象~shared_array(){}public:T&operator[](inti)const{returnpx[i];}private:T*px;shared_countpn;//必须用到引用计数器对象};#endif///////////////////////////////////////////////////////////////////////////////////////////#ifndef_CHECKED_DELETE_H_#define_CHECKED_DELETE_H_template<classT>voidchecked_array_delete(T*x){delete[]x;}template<classT>structchecked_array_deleter{public:voidoperator()(T*x)const{checked_array_delete(x);}};#endif/////////////////////////////////////////////////////////////////////////////////////////////#include<iostream>#include"shared_ptr.h"#include"shared_array.h"usingnamespacestd;/*template<classT>voidchecked_array_delete(T*x){delete[]x;}template<classT>structchecked_array_deleter{public:voidoperator()(T*x)const{checked_array_delete(x);}};写好()的重载之后,就是在shared_counted.h中释放空间时将用到。del(ptr)->del.operator()(ptr);重载了()的类使用起来就是函数对象删除器:函数对象和函数都可以充当。*/intmain(void){int*p=newint[10];shared_array<int>pa(p);for(inti=0;i<10;i++){pa[i]=i+1;}for(i=0;i<10;i++){cout<<pa[i]<<"";}cout<<endl;}
缺点:(1)、重载使用[]时要小心,shared_array不提供数组的索引范围检查
(2)、所管理的空间是死的,不能够自动增长。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。