C++ //练习 16.28 编写你自己版本的shared_ptr和unique_ptr。

C++ Primer(第5版) 练习 16.28

练习 16.28 编写你自己版本的shared_ptr和unique_ptr。

环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp 复制代码
//Shared_ptr
template <typename T> class SharedPtr {
	public:
    explicit SharedPtr(T* ptr = nullptr)
        : ptr_(ptr), ref_count_(new int(1)) {}

    SharedPtr(const SharedPtr& other)
        : ptr_(other.ptr_), ref_count_(other.ref_count_) {
        (*ref_count_)++;
    }

    SharedPtr& operator=(const SharedPtr& other) {
        if (this != &other) {
            release();
            ptr_ = other.ptr_;
            ref_count_ = other.ref_count_;
            (*ref_count_)++;
        }
        return *this;
    }

    ~SharedPtr() {
        release();
    }

    T& operator*() const {
        return *ptr_;
    }

    T* operator->() const {
        return ptr_;
    }

    T* get() const {
        return ptr_;
    }

    int use_count() const {
        return *ref_count_;
    }

	private:
    T* ptr_;
    int* ref_count_;
    void release() {
        if (--(*ref_count_) == 0) {
            delete ptr_;
            delete ref_count_;
        }
    }
};

//unique_ptr
template <typename T>class UniquePtr {
	public:
    explicit UniquePtr(T* ptr = nullptr) : ptr_(ptr) {}
    ~UniquePtr() {
        delete ptr_;
    }

    UniquePtr(const UniquePtr&) = delete;
    UniquePtr& operator=(const UniquePtr&) = delete;

    UniquePtr(UniquePtr&& other) noexcept : ptr_(other.ptr_) {
        other.ptr_ = nullptr;
    }

    UniquePtr& operator=(UniquePtr&& other) noexcept {
        if (this != &other) {
            delete ptr_;
            ptr_ = other.ptr_;
            other.ptr_ = nullptr;
        }
        return *this;
    }

    T& operator*() const {
        return *ptr_;
    }

    T* operator->() const {
        return ptr_;
    }

    T* get() const {
        return ptr_;
    }

    T* release() {
        T* temp = ptr_;
        ptr_ = nullptr;
        return temp;
    }

    void reset(T* ptr = nullptr) {
        delete ptr_;
        ptr_ = ptr;
    }

	private:
    T* ptr_;
};
相关推荐
一韦以航.2 分钟前
C【指针】详解(上)
c语言·数据结构·c++·算法
martian66524 分钟前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
HappRobot26 分钟前
python类和对象
开发语言·python
鸡吃丸子36 分钟前
React Native入门详解
开发语言·前端·javascript·react native·react.js
mit6.82437 分钟前
固定中间
算法
盼哥PyAI实验室39 分钟前
Python YAML配置管理:12306项目的灵活配置方案
开发语言·python
漂亮的小碎步丶40 分钟前
【启】Java中高级开发51天闭关冲刺计划(聚焦运营商/ToB领域)
java·开发语言
老马啸西风1 小时前
成熟企业级技术平台 MVE-010-跳板机 / 堡垒机(Jump Server / Bastion Host)
人工智能·深度学习·算法·职场和发展
hd51cc1 小时前
MFC运行时
开发语言·mfc
FMRbpm1 小时前
用队列实现栈
数据结构·c++·新手入门