#include <iostream> #include <cstdlib> class MyClass { public: void* operator new(std::size_t size) { std::cout << "Custom new operator called, size = " << size << std::endl; return std::malloc(size); } void operator delete(void* ptr) noexcept { std::cout << "Custom delete operator called" << std::endl; std::free(ptr); } void* operator new[](std::size_t size) { std::cout << "Custom new[] operator called, size = " << size << std::endl; return std::malloc(size); } void operator delete[](void* ptr) noexcept { std::cout << "Custom delete[] operator called" << std::endl; std::free(ptr); } // 构造函数和析构函数略 }; int main() { MyClass* p = new MyClass(); delete p; MyClass* arr = new MyClass[10]; delete[] arr; return 0; } 在这段代码中如何给delete加打印文件名称的功能
时间: 2024-03-11 11:49:49 浏览: 139
#include <iostream> #include<iomanip> using namespace std;九九乘法表
要在 delete 中添加打印文件名称的功能,可以使用宏定义的方式,在 delete 操作时调用自定义的 delete 函数。具体实现如下:
```
#include <iostream>
#include <cstdlib>
#define DELETE_WITH_INFO(ptr) CustomDelete(ptr, __FILE__, __LINE__)
void CustomDelete(void* ptr, const char* file, int line) noexcept {
std::cout << "Custom delete operator called from " << file << " line " << line << std::endl;
std::free(ptr);
}
class MyClass {
public:
void* operator new(std::size_t size) {
std::cout << "Custom new operator called, size = " << size << std::endl;
return std::malloc(size);
}
void operator delete(void* ptr) noexcept {
DELETE_WITH_INFO(ptr);
}
void* operator new[](std::size_t size) {
std::cout << "Custom new[] operator called, size = " << size << std::endl;
return std::malloc(size);
}
void operator delete[](void* ptr) noexcept {
DELETE_WITH_INFO(ptr);
}
// 构造函数和析构函数略
};
int main() {
MyClass* p = new MyClass();
DELETE_WITH_INFO(p);
MyClass* arr = new MyClass[10];
DELETE_WITH_INFO(arr);
return 0;
}
```
在 delete 操作时使用 DELETE_WITH_INFO 宏代替 delete 操作即可。该宏会调用 CustomDelete 函数,该函数会打印文件名称和行号,并调用 std::free() 函数释放内存。
阅读全文