#include <atomic>
template<typename T>
class ThreadSafeSharedPtr {
public:
ThreadSafeSharedPtr() : m_ptr(nullptr), m_refCount(nullptr) {}
ThreadSafeSharedPtr(T* ptr) : m_ptr(ptr), m_refCount(new std::atomic<int>(1)) {}
ThreadSafeSharedPtr(const ThreadSafeSharedPtr& other) {
m_ptr = other.m_ptr;
m_refCount = other.m_refCount;
if (m_refCount) {
m_refCount->fetch_add(1);
}
}
ThreadSafeSharedPtr& operator=(const ThreadSafeSharedPtr& other) {
if (this != &other) {
reset();
m_ptr = other.m_ptr;
m_refCount = other.m_refCount;
if (m_refCount) {
m_refCount->fetch_add(1);
}
}
return *this;
}
~ThreadSafeSharedPtr() {
reset();
}
T* get() const {
return m_ptr;
}
void reset() {
if (m_refCount && m_refCount->fetch_sub(1) == 1) {
delete m_ptr;
delete m_refCount;
}
m_ptr = nullptr;
m_refCount = nullptr;
}
T& operator*() const {
return *m_ptr;
}
T* operator->() const {
return m_ptr;
}
private:
T* m_ptr;
std::atomic<int>* m_refCount;
};
ThreadSafeSharedPtr
于 2023-07-18 12:58:28 首次发布