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_;
};
相关推荐
超级码.里奥.农几秒前
零基础 “入坑” Java--- 七、数组(二)
java·开发语言
KENYCHEN奉孝9 分钟前
Rust征服字节跳动:高并发服务器实战
服务器·开发语言·rust
挺菜的18 分钟前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
妮妮喔妮1 小时前
【无标题】
开发语言·前端·javascript
fie88891 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式
喝可乐的布偶猫1 小时前
Java类变量(静态变量)
java·开发语言·jvm
喝可乐的布偶猫2 小时前
韩顺平之第九章综合练习-----------房屋出租管理系统
java·开发语言·ide·eclipse
江山如画,佳人北望2 小时前
C#程序入门
开发语言·windows·c#
coding随想3 小时前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
凌肖战4 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode