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)、所管理的空間是死的,不能夠自動增長。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。