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_;
};
相关推荐
Tan_Ying_Y1 分钟前
什么是垃圾回收算法 他的底层原理是什么?
算法
7***37459 分钟前
Java设计模式之工厂
java·开发语言·设计模式
Xの哲學14 分钟前
Linux 分区表深度技术剖析
linux·网络·算法·架构·边缘计算
写写闲篇儿22 分钟前
经典算法题剖析之传递信息(三)
算法
上不如老下不如小23 分钟前
2025年第七届全国高校计算机能力挑战赛初赛 Python组 编程题汇总
开发语言·python·算法
程序员小白条33 分钟前
你面试时吹过最大的牛是什么?
java·开发语言·数据库·阿里云·面试·职场和发展·毕设
xlq2232242 分钟前
19.模版进阶(上)
c++
yuuki2332331 小时前
【C++】初识C++基础
c语言·c++·后端
小年糕是糕手1 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
豐儀麟阁贵1 小时前
8.2异常的抛出与捕捉
java·开发语言·python