C++ 智能指针 实现代码

智能指针的底层实现是通过 C++ 标准库提供的模板类来实现的,其中包含了一些与对象管理和资源释放相关的成员函数和成员变量。以下是一个简化版的智能指针实现,用于展示其底层实现的基本原理:

template 
class MySharedPtr {
public:
    // 构造函数,接受裸指针作为参数
    explicit MySharedPtr(T* ptr = nullptr) : m_ptr(ptr), m_refCount(new int(1)) {}

    // 拷贝构造函数
    MySharedPtr(const MySharedPtr& other) : m_ptr(other.m_ptr), m_refCount(other.m_refCount) {
        // 引用计数加1
        (*m_refCount)++;
    }

    // 析构函数
    ~MySharedPtr() {
        // 引用计数减1
        (*m_refCount)--;
        // 当引用计数为0时,删除资源
        if (*m_refCount == 0) {
            delete m_ptr;
            delete m_refCount;
        }
    }

    // 重载赋值运算符
    MySharedPtr& operator=(const MySharedPtr& other) {
        // 先释放当前对象的资源
        if (this != &other) {
            (*m_refCount)--;
            if (*m_refCount == 0) {
                delete m_ptr;
                delete m_refCount;
            }
            // 更新指针和引用计数
            m_ptr = other.m_ptr;
            m_refCount = other.m_refCount;
            (*m_refCount)++;
        }
        return *this;
    }

    // 重载解引用运算符
    T& operator*() const {
        return *m_ptr;
    }

    // 重载箭头运算符
    T* operator->() const {
        return m_ptr;
    }

private:
    T* m_ptr;               // 裸指针,指向动态分配的对象
    int* m_refCount;       // 引用计数,记录有多少个智能指针共享同一个对象
};

上面的实现是一个简化版的智能指针,它包含了一个裸指针 m_ptr 用于指向动态分配的对象,一个引用计数 m_refCount 用于记录有多少个智能指针共享同一个对象。通过在构造函数、拷贝构造函数、析构函数和赋值运算符中更新引用计数,并在引用计数为零时释放资源,从而实现了对对象生命周期的管理。

你可能感兴趣的:(c++,c++)