std::basic_ostream<CharT,Traits>::flush
来自cppreference.com
<tbody>
</tbody>
basic_ostream& flush(); |
||
向底层输出序列写入尚未提交的更改。表现为无格式输出函数 (UnformattedOutputFunction) 。
如果 rdbuf() 是空指针,那么不会构造 sentry 对象。
否则,在构造并检查 sentry 对象后,调用 rdbuf()->pubsync()。如果该调用返回 -1,那么就会调用 setstate(badbit)。
返回值
*this
异常
如果 exceptions() & badbit != 0,那么可能抛出 std::ios_base::failure。
示例
运行此代码
#include <chrono>
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
void f()
{
std::cout << "从线程输出... ";
for (int i{1}; i != 10; ++i)
{
std::this_thread::sleep_for(250ms);
std::cout << i << ' ';
// 每次输出三个数字
// 只能实时观测到该效果
if (0 == (i % 3))
std::cout.flush();
}
std::cout << std::endl; // 也会进行冲刷
}
int main()
{
std::thread tr{f};
std::this_thread::sleep_for(150ms);
std::clog << "从 main 输出\n";
tr.join();
}
输出:
从 main 输出
从线程输出... 1 2 3 4 5 6 7 8 9
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 581 | C++98 | flush() 因 LWG 问题 60 的解决方案而不表现为无格式输出函数 (UnformattedOutputFunction) |
表现为 无格式输出函数 (UnformattedOutputFunction) |
参阅
调用 sync() ( std::basic_streambuf<CharT,Traits> 的公开成员函数)
| |
[虚] |
将缓冲与关联的字符序列同步 ( std::basic_streambuf<CharT,Traits> 的虚受保护成员函数)
|
| 冲洗输出流 (函数模板) | |
输出 '\n' 并冲洗输出流 (函数模板) | |
| 与底层存储设备同步 ( std::basic_istream<CharT,Traits> 的公开成员函数)
|