手写share_ptr

share_ptr:

template <typename T>
class mysharedPtr {
public:
    mysharedPtr(T* p = NULL);
    ~mysharedPtr();
    mysharedPtr(const mysharedPtr<T>& other);
    mysharedPtr<T>& operator=(const mysharedPtr<T>& other);
private:
    T* m_ptr;
    unsigned int* m_count;
};

template <typename T>
mysharedPtr<T>::mysharedPtr(T* p) {
    m_ptr = p;
    m_count = new unsigned int(0);
    ++(*m_count);
    cout << "Constructor is succeed!" << endl;
}

template <typename T>
mysharedPtr<T>::~mysharedPtr() {
    --(*m_count);
    if ((*m_count) == 0) {
        delete[] m_ptr;
        m_ptr = NULL;
        delete[] m_count;
        m_count = NULL;
        cout << "Destructor is succeed!" << endl;
    }
}

template <typename T>
mysharedPtr<T>::mysharedPtr(const mysharedPtr<T>& other) {
    m_ptr = other.m_ptr;
    m_count = other.m_count;
    ++(*m_count);
    cout << "Copy constructor is succeed!" << endl;
}

template <typename T>
mysharedPtr<T>& mysharedPtr<T>::operator=(const mysharedPtr<T>& other) {
    // 《C++ primer》:“这个赋值操作符在减少左操作数的使用计数之前使other的使用计数加1,  
    // 从而防止自身赋值”而导致的提早释放内存  
    ++(*other.m_count);
    --(*m_count);
    // 将左操作数对象的使用计数减1,若该对象的使用计数减至0,则删除该对象  
    if ((*m_count) == 0) {
        delete[] m_ptr;
        m_ptr = NULL;
        delete[] m_count;
        m_count = NULL;
        cout << "Left side object is deleted!" << endl;
    }
    m_ptr = other.m_ptr;
    m_count = other.m_count;
    cout << "Assignment operator overloaded is succeed!" << endl;
    return *this;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值