std::cerr, std::wcerr
來自 cppreference.com
定義於標頭檔案 <iostream> |
||
extern std::ostream cerr; |
(1) | |
extern std::wostream wcerr; |
(2) | |
全域性物件 std::cerr
和 std::wcerr
控制向實現定義的型別(分別派生自 std::streambuf 和 std::wstreambuf)的流緩衝區輸出,該緩衝區關聯到標準 C 錯誤輸出流 stderr。
這些物件保證在型別為 std::ios_base::Init 的物件首次構造期間或之前被初始化,並且可用於具有有序初始化的靜態物件的建構函式和解構函式中(只要在物件定義之前包含了 <iostream>)。
除非已經發出 std::ios_base::sync_with_stdio(false),否則可以安全地從多個執行緒併發訪問這些物件,以進行格式化和非格式化輸出。
一旦初始化,(std::cerr.flags() & unitbuf) != 0(std::wcerr
亦同),這意味著傳送到這些流物件的任何輸出都將立即重新整理到作業系統(透過 std::basic_ostream::sentry 的解構函式)。
此外,std::cerr.tie() 返回 &std::cout(std::wcerr
和 std::wcout 亦同),這意味著對 std::cerr
的任何輸出操作都會首先執行 std::cout.flush()(透過 std::basic_ostream::sentry 的建構函式)。
目錄 |
[編輯] 注意
名稱中的“c”指的是“字元”(stroustrup.com FAQ);cerr
表示“字元錯誤(流)”,wcerr
表示“寬字元錯誤(流)”。
[編輯] 示例
透過 std::cerr
輸出到 stderr 會重新整理 std::cout 上待處理的輸出,而透過 std::clog 輸出到 stderr 則不會。
執行此程式碼
#include <chrono> #include <iostream> #include <thread> using namespace std::chrono_literals; void f() { std::cout << "Output from thread..."; std::this_thread::sleep_for(2s); std::cout << "...thread calls flush()" << std::endl; } int main() { std::jthread t1{f}; std::this_thread::sleep_for(1000ms); std::clog << "This output from main is not tie()'d to cout\n"; std::cerr << "This output is tie()'d to cout\n"; }
可能的輸出
This output from main is not tie()'d to cout Output from thread...This output is tie()'d to cout ...thread calls flush()
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 455 | C++98 | std::cerr.tie() 和 std::wcerr.tie() 返回空指標 |
它們分別返回 &std::cout 和 &std::wcout |
[編輯] 參閱
初始化標準流物件 ( std::ios_base 的公共成員類) | |
寫入標準 C 錯誤流 stderr (全域性物件) | |
寫入標準 C 輸出流 stdout (全域性物件) | |
與輸入流關聯的 FILE* 型別的表示式 與輸出流關聯的 FILE* 型別的表示式 與錯誤輸出流關聯的 FILE* 型別的表示式 (宏常量) |