这个智能指针的ref_count需要分配堆吗?

问题描述

enter image description here

我正在看一本书(cracking the code interview)中的智能指针实现,其内容如下:

#include<iostream>

using namespace std;

template <class T> 
class SmartPointer
{

protected:
    T* ref;
    unsigned int* ref_count;

public:
    SmartPointer(T* ptr)
    {
        ref = ptr;
        ref_count = (unsigned*)malloc(sizeof(unsigned));
        *ref_count = 1;
    }

    SmartPointer(SmartPointer<T>& sptr)
    {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++*ref_count;
    }

    SmartPointer<T> & operator=(SmartPointer<T>& sptr)
    {
        if (this != &sptr)
        {
            ref = sptr.ref;
            ref_count = sptr.ref_count;
            ++*ref_count;
        }
        return *this;
    }

    ~SmartPointer()
    {
        --*ref_count;
        if (!ref_count)
        {
            delete ref;
            free(ref_count);
            ref = NULL;
            ref_count = NULL;           
        }
    }
};

class Car
{

};

int main()
{
    SmartPointer<Car> car = new Car;
}

由于这来自有关C ++的部分:

问题1)拥有以下内容是否更有意义?

ref_count = new unsigned int ; // instead of ref_count = (unsigned*)malloc(sizeof(unsigned));

delete ref_count; // instead of free(ref_count);

问题2)还是像下面这样将ref_count放在堆栈中?

#include<iostream>

using namespace std;

template <class T> 
class SmartPointer
{

protected:
    T* ref;
    unsigned int ref_count;

public:
    SmartPointer(T* ptr)
    {
        ref = ptr;
        // ref_count = new unsigned int ; // ref_count = (unsigned*)malloc(sizeof(unsigned));
        ref_count = 1;
    }

    SmartPointer(SmartPointer<T>& sptr)
    {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++ref_count;
    }

    SmartPointer<T> & operator=(SmartPointer<T>& sptr)
    {
        if (this != &sptr)
        {
            ref = sptr.ref;
            ref_count = sptr.ref_count;
            ++ref_count;
        }
        return *this;
    }

    ~SmartPointer()
    {
        --ref_count;
        if (!ref_count)
        {
            delete ref;
            // delete ref_count; // free(ref_count);
            ref = NULL;
            // ref_count = NULL;            
        }
    }
};

class Car
{

};

int main()
{
    SmartPointer<Car> car = new Car;
}

问题3)智能指针(https://en.cppreference.com/book/intro/smart_pointers)的类型很多,上面的实现看起来像unique_prt,shared_ptr或weak_ptr?

赞赏,如果您建议使用智能指针实现,我应该看看。

解决方法

问题1)[使用new代替malloc]是否更有意义?

好的。在C ++中需要malloc的唯一原因是使用设计不良的C API要求它。无需在这里使用它。

问题2)还是像下面这样在堆栈中具有ref_count?

考虑一个指针的破坏如何影响存储在其他位置的所有其他引用计数。这是行不通的。

,

问题1)拥有以下内容是否更有意义?

由于unsigneddefault initialized(简而言之,根本没有初始化操作!),因此使用new / delete就是在使用另一对分配器/ deallocator。当然,这会使您的代码更像C ++。

问题2)还是像下面这样在堆栈中具有ref_count?

像栈一样的分配引用计数器是不可能的。您可以尝试一下,然后自己找出不可能的原因。