#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 首次发布
该文章介绍了一个模板类ThreadSafeSharedPtr,它是一个实现了多线程安全的智能指针。类中使用了std::atomic<int>来保证引用计数在并发环境下的正确性,确保在不同线程中对对象的共享和释放是安全的。成员函数包括构造、赋值、获取指针、解引用以及析构,其中析构时使用原子操作检查并减少引用计数,当计数为1时释放内存。
摘要由CSDN通过智能技术生成