【发布时间】:2023-03-04 17:42:01
【问题描述】:
有没有办法在替换的全局运算符 new 中写入文件?
// simple operator new replacment
void* operator new(std::size_t bytes) {
std::ofstream log{"log.txt"};
log << bytes << " bytes allocated\n";
return std::malloc(bytes);
}
std::ofstream 使用 new,创建一个无限循环。
【问题讨论】:
-
这通常不是一个好主意,但如果你知道 where
std::ofstream使用new可能会解决它。它是在构造函数中还是在打开文件时执行?然后你可以在第一个new被调用之前打开文件。如果它发生在<<运算符中,那么可能使用固定大小的字符串(数组)并使用snprintf格式化输出并使用write输出到文件?
标签: c++ logging new-operator ofstream dynamic-allocation