智能指针shared_ptr的实现

#include <iostream>

using namespace std;

template <class T>
class smart {
public:
    smart() = default;
    smart(T* ptr = nullptr):_ptr(ptr) {
        if (_ptr) {
            _count = new size_t(1);
        }
        else {
            _count = new size_t(0);
        }
    }

    //copy constructor
    smart(const smart &ptr) {
        if (this != &ptr) {
            this->_ptr = ptr._ptr;
            this->_count = ptr._count;
            (*this->_count)++;
        }
    }

    //operator = 
    smart operator = (const smart &ptr) {
        if (this->_ptr == ptr->_ptr) {
            return *this;
        }
        //原share_ptr引用次数减一
        if(this->_ptr) {
            *(this->_count)--;
            if (this->_count == 0) {
                delete this->_ptr;
                delete this->_count;
            }
        }
        this->_ptr = ptr._ptr;
        this->_count = ptr._count;
        *(this->_count)++;
        return *this;
    }

    //operator *
    T& operator * () {
        if (this->_ptr)
            return *(this->_ptr);
    }

    //operator ->
    T& operator -> () {
        if (this->_ptr)
            return *(this->_ptr);
    }

    ~smart() {
        *(this->_count)--;
        if (*this->_count == 0) {
            delete this->_ptr;
            delete this->_count;
        }
    }

    //return reference counting
    size_t use_count() {
        return *this->_count;
    }

    //return ptr
    T objectInPtr() {
        return *this->_ptr;
    }

    T* use_ptr() {
        return this->_ptr;
    }

private:
    T* _ptr;
    size_t* _count;
};

int main() {
    int a = 5;
    int *b = &a;
    smart<int> c(b);
    cout << c.use_count() << endl;
    smart<int> d = c;
    cout << sizeof(smart<int>) << "B" << endl;
    cout << c.use_count() << endl;
    cout << d.use_count() << endl;
    cout << "C:" << &c << "   D:" << &d << endl;
    cout << c.use_ptr() << ":" << d.use_ptr() << endl;
    cout << c.objectInPtr() << ":" << d.objectInPtr() << endl;

    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhp-purelove/p/9958479.html