使用 sync_with_stdio 时打印订单

Print order when using sync_with_stdio

看这个例子:

#include <iostream>
#include <stdio.h>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cout << "a";
    printf("b");
    std::cout << "c";
}

在 gcc 9.2 上,我得到 acb 作为输出。我期待 bac,因为如果我理解正确,std::cout 将使用它的缓冲区。为什么按这个顺序打印?

附加问题:设置std::ios::sync_with_stdio(false)会提高性能(例如在上面的例子中)?

stdout 流的默认 典型行为是行缓冲,因此输出是完全合理的。 printf 不会立即刷新,为此使用 fflush(stdout)

关于你的第二个问题,当不需要同步时,人们会期望性能会提高。不过,profile 和 check 总是更好的,显然对于这个小片段,它不会有太大影响。


编辑:已根据 .

更正答案