【发布时间】:2019-03-27 17:29:39
【问题描述】:
我已经重载了 new 和 delete 运算符来跟踪我们分配和释放内存的位置。重载的new 运算符工作正常,但是当我尝试使用重载的delete 运算符时出现错误。我希望有人可以点亮一些灯。这可能是小事。
头文件代码
void *operator new[] (size_t size, const char *file, int line, const char *function);
void operator delete(void *p, const char *file, int line, const char *function);
// other operators
#define NewWithDebug new (__FILE__, __LINE__, __FUNCTION__)
#define DeleteWithDebug delete (__FILE__, __LINE__, __FUNCTION__)
源文件代码
void *operator new (size_t size, const char *file, int line, const char *function)
{
printf("Memory Allocated (Size %zu): file= %s , function = %s , line =%d \n", size, file, function, line );
return malloc(size);
}
void *operator new[] (size_t size, const char *file, int line, const char *function)
{
printf ("Memory Allocated (Size %zu): file= %s , function = %s , line =%d \n", size, file, function, line);
return malloc(size);
}
void operator delete(void *p, const char *file, int line, const char *function)
{
printf("Memory Deallocated: file= %s , function = %s , line =%d \n", file, function, line);
free(p);
}
主要
int* Numbers = NewWithDebug int(5);
DeleteWithDebug Numbers; // <---- Error Here;
错误信息
error: expected `;' before 'Numbers
【问题讨论】:
-
你没有传递参数Numbers来删除()
-
如果我这样做
DeleteWithDebug (Numbers);,我会收到此错误,error: '(0, __FUNCTION__)' cannot be used as a function -
这就是我删除第二条评论的原因。我想了几秒钟,发现了我的错误。
-
顺便说一句,您没有在 new/delete 中调用构造函数/析构函数。您可能想使用 ::new 和 ::delete 而不是 malloc() / free。
标签: c++ operator-overloading overloading new-operator delete-operator