我已经将我的 operator new[] 覆盖为
void* operator new[](std::size_t sz, const char *file, int line)
{
void* mem = malloc(sz);
if(mem == 0){
printf("Could not allocate the desired memory, the new operator fails\n");
std::abort();
}
printf("Allocation has been done!\n");
printf("Allocation has been done! In %s, line #%i, %p[%i]\n", file, line, mem, sz);
return mem;
}
#define DEBUG_NEW2 new[](__FILE__, __LINE__)
#define new[] DEBUG_NEW2
我的程序主要用到这种new运算符,所以比较在意。 但是,编译器给我“宏名称 [-Werror] 后缺少空格”的错误消息。我试着玩弄“#define new[] DEBUG_NEW2”。在某些情况下,它编译正常,但我不会被 new[] 覆盖。
最佳答案
这里的问题是以 #define new[]
开头的行
您正在尝试创建一个名为 new[]
的宏。
首先,这是非法的,因为宏名称必须是有效的标识符,这意味着它只能包含字母、下划线、数字,并且不能以数字开头。
其次,您正试图赋予关键字新的含义。这是不允许的,意味着您的程序无效或给出未定义的行为。
不需要添加这样的宏来重载 operator new[]。事实上,您需要做的就是在所需范围内声明一个带有签名 void* operator new[](size_t)
的函数,它会自动调用以进行数组分配。
关于c++ - 内存泄漏跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14587595/