std::shared_ptr的简单实现

本文详细介绍了一种自定义的智能共享指针My_SharedPtr的实现方式,该指针可以用于C++中管理动态分配的对象,通过引用计数机制自动处理对象的生命周期,避免内存泄漏。文章深入探讨了拷贝构造、赋值操作、移动语义以及资源释放等关键概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef STD_SHAREDPTR_H
#define STD_SHAREDPTR_H
#include <stdint.h>
#include <algorithm>
using namespace std;
template<typename T>

class My_SharedPtr{

    My_SharedPtr():
        count_(new size_t),
        ptr_(nullptr){

    }

    My_SharedPtr(T* ptr):
        count_(new size_t),
        ptr_(ptr){
        *count_=1;
    }

    ~My_SharedPtr(){
        --(*count_);

        if(count_==0){
            delete ptr_;
            delete count_;
            ptr_=nullptr;
            count_=nullptr;
        }
    }

    My_SharedPtr(const My_SharedPtr& other){
        ptr_=other.ptr_;
        count_=other.count_;

        ++(*count_);
    }

    My_SharedPtr& operator=(const My_SharedPtr& other){
        ptr_=other.ptr_;
        count_=other.count_;

        ++(*count_);

        return *this;
    }

    My_SharedPtr(My_SharedPtr&& other):
        ptr_(other.ptr_),
        count_(other.count_){

        other.ptr_=nullptr;
        ++(*count_);
    }

    My_SharedPtr operator=(My_SharedPtr&& other){
        if(this!=&other){
            ptr_(other.ptr_),
            count_(other.count_){

            other.ptr_=nullptr;
            ++(*count_);
        }

            return *this;
    }
    }

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

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

        T* get(){
            return ptr_;
        }

        size_t use_count(){
            return *count_;
        }

        bool unique(){
            return *count_==1;
        }

        void Myswap(My_SharedPtr& other){
            swap(*this,other);
        }

private:

    size_t* count_;
    T* ptr_;

};

#endif // STD_SHAREDPTR_H

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值