比较完整的复现了STL中的shared_ptr中的功能,可以加载删除器,并且加入了互斥,可以在多线程中使用。
#include <iostream> #include <mutex> using namespace std; template <typename T> class Shared_ptr { public: Shared_ptr(T * t_ptrToObject) { m = new mutex(); this->haveDeleterOrNot = t_ptrToObject; this->count = malloc(sizeof(int)); (*this->count) = 1; this->haveDeleterOrNot = false; } Shared_ptr(T * t_ptrToObject, void (*t_deleter)(T *)) { this->m = new mutex(); this->ptrToObject = t_ptrToObject; this->count = (int *)malloc(sizeof(int)); (*this->count) = 1; this->deleter = t_deleter; this->haveDeleterOrNot = true; } Shared_ptr(const Shared_ptr & rhs) { this->m = rhs.m; (*m).lock(); this->ptrToObject = rhs.ptrToObject; this->count = rhs.count; (*(rhs.count)) = (*(rhs.count)) + 1; this->haveDeleterOrNot = rhs.haveDeleterOrNot; this->deleter = rhs.deleter; (*m).unlock(); } Shared_ptr & operator= (const Shared_ptr & rhs) { this->m = rhs.m; (*m).lock(); this->ptrToObject = rhs.ptrToObject; this->count = rhs.count; (*(rhs.count)) = (*(rhs.count)) + 1; this->haveDeleterOrNot = rhs.haveDeleterOrNot; this->deleter = rhs.deleter; (*m).unlock(); return (*this); } //rewrite the operator T & operator* () { return *(this->ptrToObject); } T * operator-> () { return this->ptrToObject; } ~Shared_ptr() { (*m).lock(); (*count) = (*count) - 1; if ((*count) == 0 && this->haveDeleterOrNot) { (*(this->deleter))(this->ptrToObject); } else if ((*count) == 0 && !this->haveDeleterOrNot) { delete this->ptrToObject; } (*m).unlock(); } int getCount() const{ return *this->count; } private: T * ptrToObject; int * count; bool haveDeleterOrNot; void (*deleter)(T *); mutex * m; }; void test(int * num) { cout << "num: " << *num << endl; } int main() { int * num = new int(5); Shared_ptr<int> sp1(num, test); Shared_ptr<int> sp2(sp1); Shared_ptr<int> sp3 = sp1; cout << sp1.getCount() << endl; // void (*deleter)(int *); // deleter = test; // void (*t_deleter)(int *); // t_deleter = deleter; // (*t_deleter)(num); return 0; }
标签:count,rhs,C++,Shared,shared,haveDeleterOrNot,ptr,ptrToObject From: https://www.cnblogs.com/woodx/p/16969404.html