ostream缓冲区刷新机制:flush/endl/unitbuf
请解释 ostream 的缓冲区刷新机制,包括 endl/flush/ends 的区别,unitbuf/nounitbuf 操纵器的作用,以及 tie 绑定对 cin/cout 交互的影响。
回答
屠龙少年
缓冲区刷新方式:
1. endl:插入 '\n' 并刷新缓冲区。
cout << "Hello" << endl; // 输出 + 换行 + flush
2. flush:仅刷新缓冲区(不插入字符)。
cout << "Processing..." << flush;
3. ends:插入空终止符 '\0' 并刷新(很少用)。
4. unitbuf:设置每次插入操作后自动刷新。
cout << unitbuf; // 每 << 操作后刷新
cout << nounitbuf; // 恢复缓冲
cerr 默认 unitbuf(立即输出错误)。
5. tie 绑定:
cin.tie(&cout); // 默认:cin 读取前自动刷新 cout
auto* old = cin.tie(nullptr); // 解除绑定,提升性能
性能考量:
endl频繁使用大幅降低性能(每个循环都 flush)。- 日志场景推荐
'\n'+ 适当间隔手动flush。 - 交互式应用(进度条)需要
flush。
// 高效:'\n' 不 flush
cout << "Line 1\n" << "Line 2\n";
// 按间隔 flush
cout << "Progress: " << i << '%' << flush;