std::unitbuf, std::nounitbuf
出自 cppreference.com
| 定義於標頭檔 <ios> |
||
| std::ios_base& unitbuf( std::ios_base& str ); |
(1) | |
| std::ios_base& nounitbuf( std::ios_base& str ); |
(2) | |
啟用或停用在任何輸出操作後自動刷新輸出串流。對輸入無效。
這是一個 I/O 操縱元 (manipulator),可以透過表達式如 out << std::unitbuf 用於任何類型為 std::basic_ostream 的 out,或是透過表達式如 in >> std::unitbuf 用於任何類型為 std::basic_istream 的 in。
目錄 |
[編輯] 附註
刷新操作會在 std::basic_ostream::sentry 物件的解構函式中執行;若 str.flags() & std::ios_base::unitbuf 為 true,該解構函式會呼叫 str.rdbuf()->pubsync()。
標準輸出物件 std::cerr 與 std::wcerr 預設皆已設定 unitbuf 位元。
[編輯] 參數
| str | - | I/O 串流的參考 |
[編輯] 返回值
str(操作後的串流參考)。
[編輯] 範例
若無 std::unitbuf 或其他明確的刷新操作,輸出結果相同,但不會即時顯示。
執行此程式碼
#include <chrono> #include <iostream> template<typename Diff> void log_progress(Diff d) { std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(d) << " ... "; } int main() { volatile int sink = 0; std::cout << std::unitbuf; // enable automatic flushing const auto start = std::chrono::high_resolution_clock::now(); for (int j = 0; j < 5; ++j) { for (int n = 0; n < 10000; ++n) for (int m = 0; m < 20000; ++m) sink += m * n; // do some work log_progress(std::chrono::high_resolution_clock::now() - start); } std::cout << '\n'; }
輸出
571ms ... 1146ms ... 1722ms ... 2294ms ... 2865ms ...
[編輯] 參見
| 重新整理輸出串流 (函式模板) | |
| 輸出 '\n' 並重新整理輸出串流 (函式模板) |