命名空间
变体
操作

std::unitbuf, std::nounitbuf

来自 cppreference.cn
< cpp‎ | io‎ | manip
 
 
 
输入/输出 操纵符
浮点数格式化
整数格式化
布尔格式化
字段宽度和填充控制
其他格式化
空白处理
输出刷新
(C++20)  

unitbufnounitbuf
状态标志操作
时间和货币 I/O
(C++11)
(C++11)
(C++11)
(C++11)
引用操纵符
(C++14)
 
定义于头文件 <ios>
std::ios_base& unitbuf( std::ios_base& str );
(1)
std::ios_base& nounitbuf( std::ios_base& str );
(2)

启用或禁用在任何输出操作后自动刷新输出流。对输入没有影响。

1) 在流 str 中启用 unitbuf 标志,如同调用 str.setf(std::ios_base::unitbuf) 一样。
2) 在流 str 中禁用 unitbuf 标志,如同调用 str.unsetf(std::ios_base::unitbuf) 一样。

这是一个 I/O 操纵符,可以用于表达式,例如对于任何类型为 std::basic_ostreamout,可以调用 out << std::unitbuf ;或者对于任何类型为 std::basic_istreamin,可以调用 in >> std::unitbuf

内容

[编辑] 注解

刷新在 std::basic_ostream::sentry 对象的析构函数中执行,如果 str.flags() & std::ios_base::unitbuftrue,则会调用 str.rdbuf()->pubsync()

标准输出对象 std::cerrstd::wcerr 默认设置了 unitbuf 位。

[编辑] 参数

str - I/O 流的引用

[编辑] 返回值

str (操作后的流的引用)。

[编辑] 示例

在没有 std::unitbuf 或其他显式刷新的情况下,输出是相同的,但不会实时显示。

#include <chrono>
#include <iostream>
 
template<typename Diff>
void log_progress(Diff d)
{
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d)
              << " ... ";
}
 
int main()
{
    volatile int sink = 0;
    std::cout << std::unitbuf; // enable automatic flushing
 
    const auto start = std::chrono::high_resolution_clock::now();
    for (int j = 0; j < 5; ++j)
    {
        for (int n = 0; n < 10000; ++n)
            for (int m = 0; m < 20000; ++m)
                sink += m * n; // do some work
        log_progress(std::chrono::high_resolution_clock::now() - start);
    }
    std::cout << '\n';
}

输出

571ms ... 1146ms ... 1722ms ... 2294ms ... 2865ms ...

[编辑] 参见

刷新输出流
(函数模板) [编辑]
输出 '\n' 并刷新输出流
(函数模板) [编辑]