在映射中插入地址时,新运算符重载会导致无限递归
New operator overloading causes Infinite recursion when inserting the address in a map
我正在重载新的运算符,以编写我自己的自定义内存监控类,该类具有地址到字节的映射。
但不幸的是,当我将内存的地址插入映射时,映射将创建一个新对象,重载的新运算符将再次被调用,并创建无限递归和内存泄漏。
我添加了导致以下问题的代码。请提供建议。
#include <iostream>
#include <cstdlib>
#include <map>
using namespace std;
class MemoryManager{
static map<void* const, size_t> memory; //void* is an address, size_t is size
static void allocate(void* ptr, size_t size);
}
void MemoryManager::allocate(void* ptr, size_t size){
cout << ptr << endl; // prints the address
// inserts the address of the memory in a map.
// the compiler will create `new` object and creates a recursion.
// infinite recursion is created.
memory.insert(pair<void* const, size_t>(ptr, size));
totalBytes += size;
number_of_allocations++;
}
void* operator new (size_t size){
void* ptr = malloc(size);
MemoryManager::allocate(ptr, size);
return ptr;
}
int main(){
int* p1 = new int;
}
不要那样做。
如果必须的话,可以获得"mallocator"的副本,这是世界上最简单的使用malloc的分配器,或者自己写一个。在std::map
中使用该分配器以避免它调用(非放置)new
。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 交换运算符 + 重载会导致无限递归
- 如何使用common_type和模板递归类型重载运算符+
- 重载 == 以递归方式比较两个链表
- 运算符重载流提取运算符 (>>) C++会导致无限递归流提取
- 递归调用可变参数模板函数重载时的不明确调用
- 在映射中插入地址时,新运算符重载会导致无限递归
- 通过模板函数重载以正向顺序进行模板递归(关于std::tuple上的迭代)
- 重载递归函数C++
- 递归重载"->"(成员访问)
- 重载赋值运算符导致递归警告
- 重载成员函数访问元组和递归累加结果失败的原因
- 重载放置运算符 (<<),用于递归打印出数组的元素C++
- c++中重载递归函数的模板推导规则
- >> 运算符重载函数无限递归
- c++ Boost递归变量重载apply_visitor
- 模板大小递归--构造函数多个重载
- decltype,重载运算符的递归类型推导