简单智能指针实现

时间:2021-08-29
本文章向大家介绍简单智能指针实现,主要包括简单智能指针实现使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include <iostream>
template<typename T>
class SmartPointer {
public:
    SmartPointer(T* ptr):_ptr(ptr) {
        if (ptr) _count = new size_t(1);
        else _count = new size_t(0);
    }
    SmartPointer(const SmartPointer& sp) {
        if (&sp != this) {
            _count = sp.count;
            _ptr = sp.ptr;
            ++*_count;
        }
    }
    SmartPointer& operator=(const SmartPointer& sp) {
        if (&sp == this) return *this;
        if (_ptr) {
            --*_count;
            if (_count <= 0) {
                delete _ptr; delete _count;
                _ptr = nullptr; _count = nullptr;
            }
        }
        _ptr = sp._ptr;
        _count = sp.count;
        ++_count;
        return *this;
    }
    T& operator*() {
        assert(_ptr == nullptr);
        return *_ptr;
    }
    T* operator->() {
        assert(_ptr == nullptr);
        return *_ptr;
    }
    size_t use_count() {
        return *_count;
    }
private:
    T* _ptr;
    size_t* _count; 
};

原文地址:https://www.cnblogs.com/BaymaxHH/p/15203343.html