1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #ifndef MY_SHARED_PTR #define MY_SHARED_PTR
#include<iostream> #include<functional>
template <typename T> class mySharedPtr{ private: T *ptr; std::function<void(T*)> deleter; int *ref_count; void release(){ if(--(*ref_count)==0){ if(deleter) deleter(ptr); else{ std::cerr<<"mySharedPtr default delete\n"; delete ptr; } delete ref_count; } } public: explicit mySharedPtr(T *p,std::function<void(T*)>d = nullptr): ptr(p),ref_count(new int(1)),deleter(d){} mySharedPtr(const mySharedPtr &other):ptr(other.ptr),ref_count(other.ref_count),deleter(other.deleter){ ++(*ref_count); } mySharedPtr& operator=(const mySharedPtr&other){ if(this!=&other){ release(); ptr=other.ptr; ref_count=other.ref_count; deleter=other.deleter;
++(*ref_count);
} return *this; } mySharedPtr (mySharedPtr && other) noexcept :ptr(other.ptr),ref_count(other.ref_count),deleter(other.deleter){ other.ptr=nullptr; other.ref_count=nullptr; } mySharedPtr& operator=(mySharedPtr && other) noexcept{ if(this!=&other){ release(); ptr==other.ptr; ref_count=other.ref_count; deleter=other.deleter; other.ptr=nullptr; other.ref_count=nullptr; } return *this;
} ~mySharedPtr(){ release(); } T *get() const {return ptr;} };
#endif
|