这个用于地图的参考计数内存管理器的概念好吗?
Is this concept for a reference counting memory manager for use with maps good?
我正在尝试实现一个内存管理系统来处理存储在映射中的指针。
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();
}
相关文章:
- 自定义内存管理器在发布模式下工作正常,但在调试模式下则不然
- 任务管理器 - C/C++ 应用程序 - 分配的地址空间与已用内存
- 这个用于地图的参考计数内存管理器的概念好吗?
- 用C++替换内存管理器的单例解决方案
- 用于 SDL 纹理的内存高效资源管理器
- 将全局新与自定义内存管理器结合使用
- 内存管理器-访问冲突写入位置异常
- --带有用于mpi编译的内存管理器=none标志
- 在具有动态大小内存池的多线程C/C++中实现内存管理器
- 在自定义内存管理器中使用矢量
- 删除对象时C++自定义内存管理器错误
- 在内存管理器中分配数组
- 尝试使用while循环取消分配向量,任务管理器显示内存使用正在增加
- 操作符new已在带有库的自定义内存管理器中定义
- 我们为什么要使用内存管理器
- VS2008|:任务管理器和CRT堆调试器函数之间的内存使用差异
- 类管理器-内存池
- 在c++中实现共享内存管理器
- Qt中的智能指针内存管理器
- 管理预分配块的内存管理器