【问题标题】:std::ofstream in global operator new全局运算符 new 中的 std::ofstream
【发布时间】: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 被调用之前打开文件。如果它发生在&lt;&lt; 运算符中,那么可能使用固定大小的字符串(数组)并使用snprintf 格式化输出并使用write 输出到文件?

标签: c++ logging new-operator ofstream dynamic-allocation


【解决方案1】:

您可以重载运算符,但对于特定参数,我的意思不是全局参数, 这是一个名为 student 的类的示例:

 void * operator new(size_t size)
{
    cout<< "Overloading new operator with size: " << size << endl;
    void * p = ::new student(); 
    //void * p = malloc(size); will also work fine

    return p;
}

您可以找到更多详细信息Here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2013-06-05
    • 2011-05-03
    相关资源
    最近更新 更多