Namespaces
Variants

std::basic_ostream<CharT,Traits>:: flush

From cppreference.net
basic_ostream & flush ( ) ;

将未提交的更改写入底层输出序列。行为表现为 UnformattedOutputFunction

如果 rdbuf() 是空指针,则不会构造哨兵对象。

否则,在构造并检查哨兵对象后,调用 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 << "Output from thread... ";
    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 << "Output from main\n";
    tr.join();
}

输出:

Output from main
Output from thread... 1 2 3 4 5 6 7 8 9

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 581 C++98 flush() 由于 LWG 问题 60 的解决方案
未表现为 UnformattedOutputFunction
表现为
UnformattedOutputFunction

参见

td> 同步缓冲区与关联的字符序列
( std::basic_streambuf<CharT,Traits> 的虚受保护成员函数)
调用 sync ( )
( std::basic_streambuf<CharT,Traits> 的公开成员函数)
[virtual]
刷新输出流
(函数模板)
输出 ' \n ' 并刷新输出流
(函数模板)
与底层存储设备同步
( std::basic_istream<CharT,Traits> 的公开成员函数)