1. 程式人生 > 其它 >簡單智慧指標實現

簡單智慧指標實現

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