gpt4 book ai didi

c++ - 这个用于映射的引用计数内存管理器的概念好吗?

转载 作者:行者123 更新时间:2023-11-28 02:56:14 24 4
gpt4 key购买 nike

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

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 count\n";
}

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

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

  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),但是分配在哪里?

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

ref(value);中的

value是指针?因为 value 是模板定义的类型,所以它可能不是指针。

关于c++ - 这个用于映射的引用计数内存管理器的概念好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21925429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com