为什么ofstream需要刷新?

Bre*_*ias 7 c++ file stream standard-library

如果我运行以下代码,则根本不会创建任何文件:

std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);
outputFile.write((const char*)lpResLock, dwSizeRes);
outputFile.close();
Run Code Online (Sandbox Code Playgroud)

但是,如果我在关闭之前添加flush(),它可以工作:

std::ofstream outputFile(strOutputLocation.c_str(), std::ios::binary);
outputFile.write((const char*)lpResLock, dwSizeRes);
outputFile.flush();
outputFile.close();
Run Code Online (Sandbox Code Playgroud)

标准库是否真的需要这个,或者它是Visual C++ CRT中的错误?

GMa*_*ckG 8

这是一个错误.阅读§27.8.1.10/ 4,删节:

void close();
效果:通话rdbuf()->close()......

怎么rdbuf()->close()办?根据§27.8.1.3/ 6,删节,强调我的:

basic_filebuf<charT,traits>* close();
如果is_open() == false,则返回空指针.如果存在put区域,则调用overflow(EOF)flush字符....

也就是说,它假设要冲洗.(事实上​​,呼吁flush()最终会做同样的事情.)


请注意,close()不需要调用自身,因为析构函数basic_ofstream将调用close().