命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | io‎ | basic ostream
 
 
输入/输出库
I/O 操纵符
打印函数 (C++23)
C 风格 I/O
缓冲区
(C++98/26* 已弃用,在 C++26 中移除)
抽象概念
文件 I/O
字符串 I/O
数组 I/O
(C++98/26* 已弃用,在 C++26 中移除)
(C++98/26* 已弃用,在 C++26 中移除)
(C++98/26* 已弃用,在 C++26 中移除)
同步输出
类型
错误类别接口
(C++11)
 
 
basic_ostream& flush();

将未提交的更改写入到下层输出序列。行为如同 非格式化输出函数

如果 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 << "Output from thread... ";
    for (int i{1}; i != 10; ++i)
    {
        std::this_thread::sleep_for(250ms);
        std::cout << i << ' ';
 
        // output three numbers at once;
        // the effect is observable only in real-time
        if (0 == (i % 3))
            std::cout.flush();
    }
    std::cout << std::endl; // flushes as well
}
 
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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 581 C++98 flush() 的行为不像 非格式化输出函数
因为 LWG issue 60 的决议
行为像一个
非格式化输出函数

[编辑] 参见

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