C++ shared_ptr的实现
在前面放一个源码剖析中看到的auto_ptr的定义文件,补充一点构造函数必须要为explicit,避免一些隐式转换。

补充一点:reset(rhs)函数会删除auto_ptr指向的对象,然后用rhs指向的新建一个
auto_ptr release函数意在将调⽤该函数的智能指针的所有权转移,如 ptr = my_auto2.release ();就是将my_auto2的 所有权转给ptr。
比较完整的复现了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;
}

浙公网安备 33010602011771号