sync_with_stdio(false)的副作用

sync_with_stdio()的一个特性
sync_with_stdio() 用处是“关闭同步”,从而加快cin与cout的效率。
在部分机子上如果开了这个函数cin和cout跑的还比printf和scanf快。
但是用了sync_with_stdio(false)之后不能与printf和scanf同用,否则会出错。
最近调试的时候发现的:

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    cout<<"1
";
    printf("2
");
    cout<<"3
";
    printf("4
");
}

运行结果是:

2
4
1
3

可以发现开了ios::sync_with_stdio(false)之后,printf函数被提前了,而且这与它在代码中具体出现的位置无关。
至于为什么,据说是C++为了兼容C语言,保证程序在使用std::printfstd::cout的时候不发生混乱(不发生上述情况),将输出流绑到了一起,也就是用了sync_with_stdio()函数:

如果不绑到一起(也就是开个ios::sync_with_stdio(false)),会造成指针读取的混乱,因此输出顺序混乱。
不过在测试的时候我并没有发现cin与scanf的不兼容(出于安全,还是别一起用)。

转载自:https://www.cnblogs.com/LZShuing-xuan/p/12584916.html

没有未来的未来不是我想要的未来
原文地址:https://www.cnblogs.com/Little-Turtle--QJY/p/13832888.html