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;
    };
  • 相关阅读:
    array_keys
    strval
    is_numeric
    php static延迟静态绑定
    page39 类的访问权限控制
    page34类的继承
    被遗忘在角落的类型检查函数
    2.2.5重写静态变量
    2.2.3使用parent作用域
    16个最棒的WordPress博客写作发布工具【博主桌面工具】
  • 原文地址:https://www.cnblogs.com/yongjin-hou/p/15203761.html
Copyright © 2011-2022 走看看