简单智能指针实现

#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; 
};

 

上一篇:Linux中断子系统(三)之GIC中断处理过程


下一篇:P4171 [JSOI2010] 满汉全席(2-sat)