C++ 手撕--共享式智能指针(shared_ptr)的简单实现
共享式智能指针(shared_ptr):
#include <iostream>
#include <mutex>
using namespace std;
template<typename T>
class Shared_ptr {
private:
T* ptr;
int* ref_count;
std::mutex* mtx;
void release() {
if (ref_count && --(*ref_count) == 0) {
delete ptr;
delete ref_count;
delete mtx;
}
}
public:
Shared_ptr() : ptr(nullptr), ref_count(nullptr), mtx(new std::mutex) {}
explicit Shared_ptr(T* p) : ptr(p), ref_count(new int(1)), mtx(new std::mutex) {}
Shared_ptr(const Shared_ptr& other) {
std::lock_guard<std::mutex> lock(*other.mtx);
ptr = other.ptr;
ref_count = other.ref_count;
mtx = other.mtx;
if (ref_count) {
(*ref_count)++;
}
}
Shared_ptr(Shared_ptr&& other) noexcept {
std::lock_guard<std::mutex> lock(*other.mtx);
ptr = other.ptr;
ref_count = other.ref_count;
mtx = other.mtx;
other.ptr = nullptr;
other.ref_count = nullptr;
other.mtx = nullptr;
}
Shared_ptr& operator=(const Shared_ptr& other) {
if (this != &other) {
std::lock_guard<std::mutex> lock1(*mtx);
std::lock_guard<std::mutex> lock2(*other.mtx);
release();
ptr = other.ptr;
ref_count = other.ref_count;
mtx = other.mtx;
if (ref_count) {
(*ref_count)++;
}
}
return *this;
}
Shared_ptr& operator=(Shared_ptr&& other) noexcept {
if (this != &other) {
std::lock_guard<std::mutex> lock1(*mtx);
std::lock_guard<std::mutex> lock2(*other.mtx);
release();
ptr = other.ptr;
ref_count = other.ref_count;
mtx = other.mtx;
other.ptr = nullptr;
other.ref_count = nullptr;
other.mtx = nullptr;
}
return *this;
}
T& operator*() const {
return *ptr;
}
T* operator->() const {
return ptr;
}
int use_count() const {
return ref_count ? *ref_count : 0;
}
T* get() const {
return ptr;
}
bool unique() const {
return ref_count && *ref_count == 1;
}
void reset() {
release();
ptr = nullptr;
ref_count = nullptr;
mtx = nullptr;
}
void reset(T* p) {
release();
ptr = p;
ref_count = new int(1);
mtx = new std::mutex;
}
~Shared_ptr() {
release();
}
};
标签:count,mtx,--,C++,other,Shared,shared,ref,ptr
From: https://www.cnblogs.com/mochacoco/p/18522125