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_;
};
相关推荐
coding随想34 分钟前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
凌肖战1 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
念九_ysl1 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
yaoxin5211231 小时前
124. Java 泛型 - 有界类型参数
java·开发语言
liulilittle2 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师2 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
勤奋的知更鸟2 小时前
Java 编程之模板方法模式
java·开发语言·模板方法模式
ゞ 正在缓冲99%…2 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
十年编程老舅2 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
上单带刀不带妹3 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架