shared_ptr实现

#include <bits/stdc++.h>
using namespace std;
/**
* @brief 智能指针实现
*/
template <class T>
class Test {
public:
    Test(int test):test_(test){
        cout <<"Test构造"<< endl;
    }

    void Out(T i);

    ~Test() {
        cout <<"Test析构"<< endl;
    }
int test_;
};
// 模板函数在外部定义
template<class T>
void Test<T>::Out(T i) {
    cout <<test_<<endl;
    cout <<i<<endl;
}

template <class T>
class  Shared_Ptr {
public:
    Shared_Ptr(T* ptr) {
        count_ = new int(1);
        ptr_ = ptr;
    }
    Shared_Ptr& operator=(Shared_Ptr& sptr) {
        if(sptr.ptr_ == this->ptr_) {
            return *this;
        }else {
            if(*this->count_ == 1) {
                *this->count_--;
                delete this->ptr_;
                ++*sptr.count_;
                this->ptr_ = sptr.ptr_;
                this->count_ = sptr.count_;
            }else{
                *this->count_--;
                ++*sptr.count_;
                this->ptr_ = sptr.ptr_;
                this->count_ = sptr.count_;
            }
        }
        cout <<"引用计数 = "<<*this->count_<< endl;
    }

    ~ Shared_Ptr() {
        if(*count_ == 1) {
            *count_--;
            cout <<"释放资源"<< endl;
            delete ptr_;
        }else {
            cout <<"引用计数--"<< endl;
            *count_--;
        }
    }

private:
    int* count_ = nullptr;
    T* ptr_;
};

int main() {
    // Shared_Ptr<Test> ptr(new Test(0)); 
    // Shared_Ptr<Test> nptr(new Test(1));
    // nptr = ptr; 
    // Test* ptr = new Test(0);
    // delete ptr;
    // shared_ptr<Test> ptr(new Test(0));
    // cout << sizeof(ptr) << endl;
    Test<int> t(1);
    t.Out(1);
    return 0;
}
  • 思想就是利用一个引用计数指针,一个指向管理对象的指针,然后重载operator=运算符。
  • 需要注意的就是:类模板在外部使用上需要明确类型,类模板的模板函数在外部定义时也是需要明确类型,但是在声明class的时候不需要明确类型。
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值