C++实现share_ptr
提示:以下是本篇文章正文内容,下面案例可供参考
接上一章C++实现vector
继续记录复习面经
C++实现share_ptr
#include <mutex>
using namespace std;
template<class T>
class my_shareptr {
public:
//指针参数的构造函数
my_shareptr(T* _ptr) :ptr(_ptr) {
count = new int(1);
mt = new mutex;
}
//my_shareptr参数的拷贝构造函数
my_shareptr(my_shareptr<T>& sptr) :
ptr(sptr.ptr),
count(sptr.count),
mt(sptr.mt) {
AddCount();
}
~my_shareptr() {
relese();
}
//重载 " = " 需要先将原来的指针释放
my_shareptr<T>& operator =(my_shareptr<T>& sptr) {
relese();
ptr = sptr.ptr;
count = sptr.count;
mt = sptr.mt;
AddCount();
return *this;
}
//解引用
T& operator* () {
return (*ptr);
}
T* operator ->() {
return ptr;
}
int getCount() {
return (*count);
}
private:
//计算器增加
void AddCount() {
mt->lock();
(*count)++;
mt->unlock();
}
//如果无指针的引用则释放该指针和计数器引用
void relese() {
bool falg = false;
mt->lock();
if ((*count)-- == 0) {
delete ptr;
delete count;
ptr = nullptr;
count = nullptr;
falg = true;
}
mt->unlock();
if (falg) {
delete mt;
mt = nullptr;
}
}
private:
T* ptr;
int* count;
mutex* mt;
};
测试share_ptr
int main() {
my_shareptr<my_vector<int>> sp (new my_vector<int>);
sp.operator*().push_back(4254);
cout << sp.getCount() << endl;
my_shareptr<my_vector<int>> ssp(sp);
cout << sp.getCount() << endl;
cout << (sp.operator*())[0] << endl;
cout << ssp.getCount() << endl;
cout << (ssp.operator*())[0] << endl;
}