static ofstream会创建一个文件,但永远不会写入它?

时间:2018-02-14 03:27:52

标签: c++ winapi

我有一个将一些数据写入文件的函数:

void log(const std::string& data) 
{
    std::ofstream out_file{ "data.txt", std::ofstream::app };
    out_file << data;
}

这完全没问题。但是,第二个我将out_file声明更改为static,它将创建data.txt文件,但它实际上永远不会向其写入任何数据。

不会抛出任何异常,但即使多次调用日志函数,文件也将始终为空。如果我删除static,则日志记录功能将正常工作并写入文件。

在低级键盘钩子回调中调用此函数。 MSDN声明:This hook is called in the context of the thread that installed it.所以它不应该是与线程相关的问题。

1 个答案:

答案 0 :(得分:2)

问题是对无法保证的全球对象的适当破坏。通过在我的代码中添加以下内容:

out_file << data << std::flush;

这一切都按预期工作。