16.26
用函数指针来实现删除器,想不出来时候多睡一会
template <typename T, typename Func = default_delete<T>*>
class my_shared_ptr {
public:
my_shared_ptr(Func func = 0) :data(nullptr), useCount(new int(1)),del(a) {
}
my_shared_ptr(T* value, Func func = 0):data(value), useCount(new int(1)), del(func) {
}
my_shared_ptr(const my_shared_ptr& msp, Func func = 0):data(msp.data),use_count(msp.useCount), del(func) {
if(*useCount){
++*useCount;
}
}
my_shared_ptr& operator=(const my_shared_ptr& msp){
if(--*useCount == 0){
delete data;
delete useCount;
}
data = msp.data;
useCount = msp.useCount;
++*useCount;
return *this;
}
size_t use_count(){
return use_count;
}
T* get() {
return data;
}
void swap(my_shared_ptr& msp){
std::swap(this->data, msp.data);
}
void reset(my_shared_ptr& data){
free();
this->data = data.data;
this->useCount = data.useCount;
++*data.use_count;
}
bool unique(){
if(*useCount == 1){
return true;
}
return false;
}
T& operator*() { return *p; }
T& operator*() const { return *p; }
~my_shared_ptr(){
free();
}
private:
void free(){
if (--*useCount == 0) {
cout << del << endl;
del ? (*del)(data) : delete data;
}
}
T* data;
int* useCount;
Func del = 0;
};
unique_ptr类同
template <typename T, typename Func = default_delete<T>*>
class my_unique_ptr {
public:
my_unique_ptr(T* data, Func func = 0): data(data), del(func){}
T* release(){
T* tmpData = data;
data = 0;
return tmpData;
}
void reset(){
data = 0;
}
void reset(T* p){
delete data;
data = p;
}
~my_unique_ptr(){
del ? (*del)(data) : delete data;
}
private:
T* data;
Func del = 0;
};
16.29
略
16.30
略
16.31
将DebugDelete()作为函数指针传入,判断当前是否存在该指针来判断是否使用删除器
16.32