c++ 智能指针 share_ptr 简单实现

#include <pthread.h>
#pragma comment(lib,"x86/pthreadVC2.lib")
using namespace std;

template <typename T>
class Shared_ptr {
public:
    Shared_ptr(){
        count = 0;
        _ptr = (T*)0;
        pthread_mutex_init(&mutex, NULL);
    }

    Shared_ptr(T* p){
        count = new int(1);
        _ptr = p;
        pthread_mutex_init(&mutex, NULL);
    }

    Shared_ptr(Shared_ptr<T>& other){
        pthread_mutex_init(&mutex, NULL);

        pthread_mutex_lock(&mutex);
        count = &(++ *other.count);
        _ptr = other._ptr;
        pthread_mutex_unlock(&mutex);
    }

    T* operator->(){ 
        return _ptr; 
    }

    T& operator*() {
        return *_ptr;
    }

    Shared_ptr<T>& operator=(Shared_ptr<T>& other) {
        if (this == &other){
            return *this;
        }

        ++(*other.count);

        pthread_mutex_lock(&mutex);
        if (this->_ptr && 0 == --(*this->count)){
            delete count;
            delete _ptr;
            cout << "delete ptr =" << endl;
        }

        this->_ptr = other._ptr;
        this->count = other.count;
        pthread_mutex_unlock(&mutex);

        return *this;
    }

    ~Shared_ptr(){
        if (_ptr && --(*count) == 0){
            pthread_mutex_lock(&mutex);
            delete count;
            delete _ptr;
            pthread_mutex_unlock(&mutex);
            cout << "Delete ptr" << endl;
        }
    }
    int getRef() { 
        return *count;
    }
private:
    int* count;
    T* _ptr;
    pthread_mutex_t mutex;
};

int main(int argc, const char * argv[])
{
    Shared_ptr<string> pstr(new string("abc"));
    cout << "Pstr:" << pstr.getRef() << " " << *pstr << endl;

    Shared_ptr<string> pstr2(pstr);
    cout << "Pstr:"  << pstr.getRef()  << " "<< *pstr << endl;
    cout << "pstr2:" << pstr2.getRef() << " "<< *pstr2 << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值