c++ - 如何在 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;
}
解决方案
这是一个非常肮脏的解决方案,但可能对您的具体情况有所帮助:
#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
...
};
推荐阅读
- node.js - 访问 Azure 计费 API
- awk - sed 在第二个管道符号前面的所有内容
- symfony - 如何在 twig 中访问关系 imageName(使用 VichUploaderBundle)
- php - Codeigniter 3.1.4 发布请求未收到表单数据参数
- json - 对数组中的某些对象属性进行 JSON 模式条件检查
- sql - SQL - 按结果分组
- macos - 使用具有提升权限的 Touch ID
- c# - 在链接实体中构建具有特定字段的 lambda 表达式树
- python - 字数引擎,输出使用方括号和顺序不正确
- javascript - 在 DOM 之后加载 Angular 数据