天天看點

C++重新整理緩沖區

今天看到有段代碼在輸出的時候用到了cout << n << std::flush; 從名稱來看知道std::flush的作用肯定是重新整理緩沖區,但是測試一下他與cout << n; 感覺沒有任何差別。于是隻能問度娘了。果然頗有收獲。cout << n; 是系統每隔一段時間進行檢測輸出的。但是由于間隔比較短,讓人以為和沒有flush一樣。而且還知道了,cout << n << std::endl 的作用不止是回車換行,他還有重新整理緩沖區的作用。c++中還有ends,unitbuf,nounitbuf等用來重新整理緩沖區,簡單來說重新整理緩沖區的作用就是為了讓緩沖區的資訊立即強制輸出。

下面有一段代碼讓你對重新整理緩沖有明顯的概念:

#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
	setvbuf(stdout, NULL, _IOLBF, 1024);  //設定控制台輸出為行緩存模式,把緩沖區與流相關 
	cout << "hello world\n" << flush;
	cout << "hello world\n";
	Sleep(5000);
	cout << "leeboy" << endl;

	system("pause");
	return 0;
}
           

是以程式設計要形成好的習慣,記得重新整理緩沖區。