#include <iostream>
#include <atomic>
template <typename T>
class shared_ptr {
private:
T* ptr; // 指向管理的对象
std::atomic<int>* count; // 引用计数
void release() {
if (ptr && --(*count) == 0) {
delete ptr;
delete count;
}
}
public:
// 构造函数
explicit shared_ptr(T* p = nullptr) : ptr(p), count(new std::atomic<int>(1)) {
if (ptr == nullptr) {
*count = 0;
}
}
// 拷贝构造函数
shared_ptr(const shared_ptr& other) : ptr(other.ptr), count(other.count) {
if (ptr) {
++(*count);
}
}
// 赋值运算符
shared_ptr& operator=(const shared_ptr& other) {
if (this != &other) {
release();
ptr = other.ptr;
count = other.count;
if (ptr) {
++(*count);
}
}
return *this;
}
// 析构函数
~shared_ptr() {
release();
}
// 重载解引用运算符
T& operator*() const { return *ptr; }
// 重载箭头运算符
T* operator->() const { return ptr; }
// 获取原始指针
T* get() const { return ptr; }
// 重置指针
void reset(T* p = nullptr) {
if (p != ptr) {
release();
ptr = p;
count = new std::atomic<int>(1);
if (ptr == nullptr) {
*count = 0;
}
}
}
// 获取引用计数
long use_count() const { return *count; }
};
// 测试代码
int main() {
shared_ptr<int> sp1(new int(10));
std::cout << "sp1 use count: " << sp1.use_count() << std::endl; // 输出: 1
{
shared_ptr<int> sp2 = sp1;
std::cout << "sp1 use count: " << sp1.use_count() << std::endl; // 输出: 2
std::cout << "sp2 use count: " << sp2.use_count() << std::endl; // 输出: 2
}
std::cout << "sp1 use count: " << sp1.use_count() << std::endl; // 输出: 1
return 0;
}
标签:count,const,return,other,shared,ptr,模拟
From: https://www.cnblogs.com/chhblogs/p/18672655