在映射中插入地址时,新运算符重载会导致无限递归

New operator overloading causes Infinite recursion when inserting the address in a map

本文关键字:重载 递归 无限 运算符 映射 插入 地址      更新时间:2023-10-16

我正在重载新的运算符,以编写我自己的自定义内存监控类,该类具有地址到字节的映射。

但不幸的是,当我将内存的地址插入映射时,映射将创建一个新对象,重载的新运算符将再次被调用,并创建无限递归和内存泄漏。

我添加了导致以下问题的代码。请提供建议。

#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