zoukankan      html  css  js  c++  java
  • 智能指针 shared_ptr 简易实现(C++)

    template <typename T>
    class shared_ptr {
    private:
        int* count; // 引用计数,不同shared_ptr指向同一引用计数
        T* ptr; // 模板指针ptr,不同shared_ptr指向同一对象
    
    public: 
        // 构造函数
        shared_ptr(T* p) : count(new int(1)), ptr(p) {}
    
        // 复制构造函数,引用计数+1
        shared_ptr(shared_ptr<T>& other) : count(&(++* other.count)), ptr(other.ptr) {}
    
        T* operator->()  return ptr;
        T& operator*()  return *ptr;
    
        // 赋值操作符重载
        shared_ptr<T>& operator=(shared_ptr<T>& other) {
            ++* other.count;
            // 如果原shared_ptr已经指向对象
            // 将原shared_ptr的引用计数-1,并判断是否需要delete
            if (this->ptr &&  -- *this->count==0 ) {
                delete count;
                delete ptr;
            }
            // 更新原shared_ptr
            this->ptr = other.ptr;
            this->count = other.count;
            return *this;
        }
    
        // 析构函数
        ~shared_ptr() {
            // 引用计数-1,并判断是否需要delete
            if (-- * count == 0) {
                delete count;
                delete ptr;
            }
        }
    
        // 获取引用计数
        int getRef()  return *count;
    };
  • 相关阅读:
    CF869E The Untended Antiquity 解题报告
    Walk 解题报告
    CF911F Tree Destruction 解题报告
    P4397 [JLOI2014]聪明的燕姿
    洛谷 P2329 [SCOI2005]栅栏 解题报告
    洛谷 P3747 [六省联考2017]相逢是问候 解题报告
    set-erase
    set-empty
    set-empty
    set-end
  • 原文地址:https://www.cnblogs.com/yongjin-hou/p/15203761.html
Copyright © 2011-2022 走看看