Interview_C++_day11

摸鱼的一天。。

\(shared\_ptr\) 指针的实现

template<typename T> class Shared_ptr {
private:
    T *ptr;
    int *use_count; // 用指针保证指向同一块地址
public:
    Shared_ptr() {
        ptr = nullptr;
        use_count = nullptr;
        cout << "Created" << endl;
    }
    Shared_ptr(T *p){
        ptr = p;
        use_count = new int(1);
        cout << "Created" << endl;
    }
    Shared_ptr(const Shared_ptr<T> &other) {
        ptr = other.ptr;
        ++(*other.use_count);
        use_count = other.use_count;
        cout << "Created" << endl;
    }
    Shared_ptr<T>& operator=(const Shared_ptr &other) {
        if(this == &other)  return *this;
        (*other.use_count)++;
        if(ptr && --(*use_count) == 0) {
            delete ptr;
            delete use_count;
        }
        ptr = other.ptr;
        use_count = other.use_count;
        return *this;
    }
    T& operator*() {    // 返回指针的引用
        return *ptr;
    }
    T* operator->() {
        return ptr;
    }
    int get_use_count() {
        if(use_count == nullptr)    return 0;
        return *use_count;
    }
    ~Shared_ptr() {
        if(ptr && --(*use_count) == 0) {
            delete ptr;
            delete use_count;
            cout << "Destroy" << endl;
        }
    }
};

原文链接: https://www.cnblogs.com/Jiaaaaaaaqi/p/12327488.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Interview_C++_day11

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/330204

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午5:28
下一篇 2023年3月1日 下午5:28

相关推荐