sync_with_stdio(false)的副作用

sync_with_stdio()的一个特性

水一篇随笔
其实对于用快读的大佬来说没什么用,但还是提一下
ios::sync_with_stdio(false)用处是“关闭同步”,从而加快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\n";
    printf("2\n");
    cout<<"3\n";
    printf("4\n");
}

运行结果是:

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的不兼容(出于安全,还是别一起用)。

posted @ 2020-03-27 22:50  LZShuing  阅读(776)  评论(3编辑  收藏  举报