温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

shared_array

发布时间:2020-06-28 11:00:51 来源:网络 阅读:588 作者:汇天下豪杰 栏目:编程语言

1、上次写的删除器有些问题:

template<class P, class D>
class sp_counted_impl_pd : public sp_counted_base{
public:
    sp_counted_impl_pd(P p, D d) : ptr(p), del(d){}
public:
    void dispose(){
        del(ptr);  //就是这里,将对象用作函数!!!
    }
private:
    P ptr;
    D del;
};

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>
using namespace std;
using namespace boost;

int main(void){
    int *p = new int[10];
    shared_array<int> pa(p);  //共享数组

    for(int i = 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<class T>
class shared_array{
public:
    typedef checked_array_deleter<T> deleter;
    shared_array(T *p = 0) : px(p), pn(p, deleter()){} //无名对象
    ~shared_array(){
        
    }
public:
    T& operator[](int i)const{
        return px[i];
    }
private:
    T *px;
    shared_count pn;  //必须用到引用计数器对象
};

#endif
///////////////////////////////////////////////////////////////////////////////////////////
#ifndef _CHECKED_DELETE_H_
#define _CHECKED_DELETE_H_

template<class T>
void checked_array_delete(T *x){
    delete []x;
}

template<class T>
struct checked_array_deleter{
public:
    void operator()(T *x)const{
        checked_array_delete(x);        
    }
};

#endif
/////////////////////////////////////////////////////////////////////////////////////////////
#include<iostream>
#include"shared_ptr.h"
#include"shared_array.h"
using namespace std;
/*
template<class T>
void checked_array_delete(T *x){
    delete []x;
}

template<class T>
struct checked_array_deleter{
public:
    void operator()(T *x)const{
        checked_array_delete(x);        
    }
};
写好()的重载之后,就是在shared_counted.h中释放空间时将用到。
del(ptr)  -> del.operator()(ptr);重载了()的类使用起来就是函数对象
删除器:函数对象和函数都可以充当。
*/
int main(void){
    int *p = new int[10];
    shared_array<int> pa(p);

    for(int i = 0; i < 10; i++){
        pa[i] = i+1;
    }
    for(i = 0; i < 10; i++){
        cout<<pa[i]<<" ";
    }
    cout<<endl;
}

  缺点:(1)、重载使用[]时要小心,shared_array不提供数组的索引范围检查

  (2)、所管理的空间是死的,不能够自动增长。




向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI