全局重载c ++中的New和Delete运算符

问题描述 投票:-2回答:1

我已经超载了newdelete运算符来跟踪我们分配和释放内存的位置。重载的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

c++ operator-overloading overloading new-operator delete-operator
1个回答
0
投票

您的问题是您不允许使用带有删除表达式的放置删除操作符:see here。它们仅在放置新表达式在构造函数中遇到异常时调用。

从上面

如果构造函数抛出异常,则必须在将异常传播回执行放置新表达式的代码之前释放该存储,这就是放置删除函数的目的。

© www.soinside.com 2019 - 2024. All rights reserved.