c++实现引用计数智能指针

本文介绍了一种模板类实现的智能引用计数管理方法,通过构造函数、复制构造函数及赋值运算符重载来自动管理对象引用计数,确保资源正确释放。此方法适用于多种数据类型,并能有效避免内存泄漏。

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

主要的思路是使用一个int* 的指针进行计数,在构造函数时候设置为0,并加1(或者直接设置为1)。然后赋值和复制构造时候把int* 和数据保存的指针T* mP传到另外一个类中。在赋值的时候要注意左边的指针是否已经有数据了,有数据就要先-1,然后再进行赋值。

template<typename T>
class ref1
{
public:
    explicit ref1(T* p = NULL) : mP(p), sCount(new int)
    {
        *sCount = 0;
        ++(*sCount);

        std::cout << "constructor" << std::endl;
        std::cout << *sCount << std::endl;
    }

    ref1(const ref1& copy)
    {
        if (this != &copy)
        {
            this->mP = copy.mP;
            this->sCount = copy.sCount;
            ++(*sCount);

            std::cout << "copy " << std::endl;
            std::cout << *sCount << std::endl;
        }
    }

    ref1& operator=(const ref1& rhs)
    {
        if (mP == rhs.mP)
        {
            return *this;
        }

        std::cout << "= construct2 " << std::endl;
        std::cout << *sCount << std::endl;
        //原来已经有一个对象了
        if (sCount > 0)
        {
            std::cout << *sCount << std::endl;
            --(*sCount);

            std::cout << *sCount << std::endl;

            if (*sCount == 0)
            {
                std::cout << "delete other" << std::endl;

                if (mP != nullptr)
                {
                    delete mP;
                    mP = nullptr;
                }

                if (sCount != nullptr)
                {
                    delete sCount;
                    sCount = nullptr;
                }                
            }
        }
        
        this->mP = rhs.mP;
        this->sCount = rhs.sCount;
        ++(*sCount);

        std::cout << "= construct " << std::endl;
        std::cout << *sCount << std::endl;
        return *this;
    }

    ~ref1()
    {
        --(*sCount);
        std::cout << "deconstruct " << std::endl;
        std::cout << *sCount << std::endl;

        if (*sCount == 0)
        {
            std::cout << "delete" << std::endl;

            if (mP != nullptr)
            {
                delete mP;
                mP = nullptr;
            }

            if (sCount != nullptr)
            {
                delete sCount;
                sCount = nullptr;
            }
        }
    }

protected:
    int *sCount;

    T* mP;

    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值