您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-19 14:08 501 查看
主要的思路是使用一个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 != ©)

        {

            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;

    

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: