我的问题不是
Is it safe to `free()` memory allocated by `new`?的重复.
我正在为POD编写一个玩具垃圾收集器,其中我定义了我自己的定制运算符new / new []和operator delete / delete [].代码如下:
#include <iostream> #include <map> std::map<void*,std::size_t> memory; // globally allocated memory map struct collect_t {} collect; // tag for placement new void* operator new(std::size_t size,const collect_t&) { void* addr = malloc(size); memory[addr] = size; return addr; } void* operator new[](std::size_t size,const collect_t&) { return operator new(size,collect); } void operator delete(void *p,const collect_t&) noexcept { memory.erase(p); // should call ::operator delete,no recursion free(p); } void operator delete[](void *p,const collect_t&) noexcept { operator delete(p,collect); } void display_memory() { std::cout << "Allocated heap memory: " << std::endl; for (auto && elem : memory) { std::cout << "\tADDR: " << elem.first << " " << "SIZE: " << elem.second << std::endl; } } void clear() { for (auto && elem : memory) free(elem.first); // is this safe for arrays? memory.clear(); } int main() { // use the garbage collector char *c = new(collect) char; int *p = new(collect) int[1024]; // true size: sizeof(int)*1024 + y (unknown overhead) display_memory(); clear(); display_memory(); }
这个想法很简单:我将所有分配的跟踪地址(分配给我的自定义新的地址)存储在std :: map中,并确保在一天结束时清除我的clear()函数中的所有内存.我为我的新的和删除使用一个标签(并且不重载全局的),以便std :: map的分配器可以调用全局而不重复.
我的问题如下:在我的clear()函数中,我在行中取消分配内存
for (auto && elem : memory) free(elem.first); // is this safe for arrays?
这对阵列是安全的,例如for int * p = new(collect)int [1024];?我相信是因为void * operator new [](std :: size_t size,const collect_t&)调用operator new(size,collect);后者调用malloc.我不是100%肯定的,可以吗?