首页 > 解决方案 > 如何在 C++ 中重载“删除”运算符以打印使用它的文件的行和名称?

问题描述

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

#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;
}

标签: c++compiler-errorsmacrosoverloadingdelete-operator

解决方案


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

#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
  ...
};

推荐阅读