如何在 C++ 中重载 "delete" 运算符以打印使用它的文件的行和名称?

How to overload "delete" operator in C++ to print the line and name of the file where it is used?

我正在尝试重载“删除”运算符以在控制台中打印使用它的文件的行号和名称。我尝试了以下方法:

#include <iostream>

void operator delete(void* adress, char* file, int line) {
    printf("%s: line %d -> ", file, line);
    delete(adress);
}

#define delete delete(__FILE__, __LINE__)

int main() {
    int* x = new int;
    delete x;
}

但是我得到这个编译错误(msvc,C++17):

Error C2146 syntax error: missing ';' before identifier 'x'

我找不到任何解决方法。我该如何解决这个问题?

编辑:这是适用于“新”运算符的类似内容:

#include <iostream>

using namespace std;

void* operator new(std::size_t size) {
    void* ptr = malloc(size);
    /* ... */
    return ptr;
}

void* operator new(std::size_t size, const int line, const char* const file) {
    printf("%s: line %d -> ", file, line);
    // BOTH RETURNS WORK
    //return malloc(size);
    return ::operator new(size);
}

#define new new(__LINE__, __FILE__)

int main() {
    int* x = new int;
    //delete x;
}

这是一个非常肮脏的解决方案,但可能对您的具体情况有所帮助:

#define delete cout << __FILE__ << " " << __LINE__ << endl, delete

但是,有一个很强的限制:如果一个函数被声明为=delete

,它将不起作用
class SomeClass
{
  ...
  void fn() = delete;  // This will not compile
  ...
};

然后必须使用类似这样的东西:

class SomeClass
{
  ...
#undef delete
  void fn() = delete;
#define delete cout << __FILE__ << " " << __LINE__ << endl, delete
  ...
};