簡體   English   中英

在映射中插入地址時,新的運算符重載會導致無限遞歸

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

我正在使新運算符重載,以編​​寫自己的自定義內存監視類,該類具有地址到字節的映射。

但是不幸的是,當我將內存地址插入到映射中時,該映射將創建一個新對象,並且重載的new運算符將再次被調用,並造成無限遞歸和內存泄漏。

我添加了導致以下問題的代碼。 請指教。

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM