这个用于地图的参考计数内存管理器的概念好吗?

Is this concept for a reference counting memory manager for use with maps good?

本文关键字:管理器 内存 用于 地图 参考      更新时间:2023-10-16

我正在尝试实现一个内存管理系统来处理存储在映射中的指针。

struct refmanager{ //since this class is only for inheritance
//and not for polymorphism their does not need to be a virtual destructor
int count;
refmanager():count(0){}

};

我的第一个想法是将上述结构继承到我将作为指针插入到映射中的类中。

    template <class P> void ref(P ptr)
{
    ptr->count+=1;
    cout<<"increasing ref countn";
}
template <class P> void deref(P ptr)
{
    ptr->count-=1;
    cout<<"decreasing ref countn";
    if (ptr->count==0)
        delete ptr;
}

比我打算使用上面的模板函数来增加和减少引用计数。为了使系统自动化,我将使用以下模板函数作为法线贴图方法的替代品(请注意,这并不完整,清除地图方法是为我的测试用例编写的,不是通用的)。

  template <class M, class K, class V> void mapinsert(M &map, K key, V value)
{
    ref(value);
    map.insert(pair<K, V>(key, value));
}

template <class T> void clearmap(T input)
{
    deref(input[1]);
    input.clear();
}

从初步测试来看,这个想法是可行的。但我不知道这是否会导致以后可能发生的灾难。有更多经验的人可以让我知道这个内存管理概念是否有任何好处,如果不是,它何时、何地以及为什么会失败?

我只看参考对象(delete ptr)的空间释放,但是分配在哪里?

必须确保每个引用对象都在堆中分配,而不是在堆栈中分配。

value ref(value);是指针?由于value是模板定义的类型,因此它可能不是指针。

显然我不能在注释中输入代码。无论如何,这是对查理斯回答的回应。顺便说一下,他是对的,上面的方法是可行的,但不是最安全的方法。以下是更安全的方法。

您可以使用以下代码生成 refmanger 类:

class refmanager{
private:
    int count;
public:
    refmanager():count(0){}
    virtual ~refmanager() {}
    void ref(refmanager* ptr)
    {
        ptr->count+=1;
    }
    void deref(refmanager* ptr)
    {
        ptr->count-=1;
        if (ptr->count==0)
            delete ptr;
    }
};

refmanager 类可以由需要管理其指针引用的类继承。

下面的代码现在只会在 V 和 T 是包含具有正确格式的 ref 和 deref 方法的对象时进行编译。换句话说,您确保代码在运行过程中不会意外崩溃。

template <class M, class K, class V> void mapinsert(M &map, K key, V value)
{
    value->ref(value);
    map.insert(pair<K, V>(key, value));
}
template <class T> void clearmap(T input)
{
    input[1]->deref(input[1]);
    input.clear();
}