c++ - 试图了解刷新缓冲区问题的影响
问题描述
我是 C++ 的初学者,所以如果我的问题听起来很愚蠢或其他什么,我深表歉意。
我一直在阅读一本关于流缓冲区的简单介绍的书,在某些情况下刷新缓冲区很重要,因此为了理解效果,我运行了以下代码:
代码1:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " ";
this_thread::sleep_for(chrono::seconds(1));
}
cout << endl;
return 0;
}
代码2:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " << flush;
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
}
两个代码都给出相同的输出,完全没有区别,它们打印 1 sleep for 1 second then 2, sleep for another second,依此类推。
我尝试在 DevC++ 和 CodeBlocks 中运行代码,结果相同。
书上说code1的结果——>“程序等待5秒,一次打印所有数字”,code2的结果——>“程序打印数字等待1秒,打印第二个数字和很快”。
我真的不明白出了什么问题。
解决方案
这是一个带有和不带有异常的刷新的示例(它应该在最后一行被刷新之前终止程序):
#include <iostream>
int main() {
std::cout << "test with flush" << std::flush;
std::cout << "test without flush";
throw;
}
当编译并在godbolt中运行时,我看到:
Program returned: 139
terminate called without an active exception
test with flush
但没有提到“没有刷新的测试”,因为程序在它可以自动刷新之前就结束了。
推荐阅读
- python - Django REST Framework Viewset 返回 404(GET 请求)
- docker - 如何从其哈希中找出 Docker 镜像层是什么?
- javascript - 如何从 Google 表格中的元素更新表单?
- flutter - 如何对文本进行排序,使其喜欢左侧的第一行(“abcd”),右侧的(“$ 1000”),而(“prod amount”)在它的下一行?(扑)
- python - Python 3.8.2| 为什么我有一个:TypeError: cannot unpack non-iterable NoneType object?
- javascript - 问剑道ui,如何使用ajax从另一个页面调用数据?
- gradle - 如何在gradle上传递系统系统属性“-D”
- android - 如何使用 sourceSets 排除aidl文件
- linker - 导入到 python 时使用 Boost.python 包装 C++ 模块时的未定义符号
- scala - Spark中的Kmeans算法,