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++11并发支持库
开发语言·c++·多线程·c++11·c++并发支持库
小灰灰搞电子8 分钟前
Rust可以取代C++么?
开发语言·c++·rust
Swizard12 分钟前
别再只会算直线距离了!用“马氏距离”揪出那个伪装的数据“卧底”
python·算法·ai
cat三三13 分钟前
java之异常
java·开发语言
奇树谦15 分钟前
【Qt实战】实现图片缩放、平移与像素级查看功能
开发语言·qt
我命由我1234522 分钟前
Python Flask 开发问题:ImportError: cannot import name ‘Markup‘ from ‘flask‘
开发语言·后端·python·学习·flask·学习方法·python3.11
wjs202424 分钟前
Go 语言指针
开发语言
flashlight_hi32 分钟前
LeetCode 分类刷题:199. 二叉树的右视图
javascript·算法·leetcode
LYFlied34 分钟前
【每日算法】LeetCode 46. 全排列
前端·算法·leetcode·面试·职场和发展