Namespaces
Variants

std:: cerr, std:: wcerr

From cppreference.net
< cpp ‎ | io
定義済みヘッダー <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 についても同様)となり、これらのストリームオブジェクトに送信される出力はすべて直ちにOSにフラッシュされる( std::basic_ostream::sentry のデストラクタ経由)。

さらに、 std :: cerr . tie ( ) & std:: cout を返します( std::wcerr std::wcout についても同様です)。これは、 std::cerr に対する出力操作が行われる前に、常に std:: cout . flush ( ) が実行される( std::basic_ostream::sentry のコンストラクタ経由で)ことを意味します。

目次

注記

名前の「c」は「character」(文字)を指します( stroustrup.com FAQ ); cerr は「character error (stream)」(文字エラー(ストリーム))を意味し、 wcerr は「wide character error (stream)」(ワイド文字エラー(ストリーム))を意味します。

stderr への出力は、 std::cerr を介して行うと std::cout の保留中の出力をフラッシュするが、 stderr への出力を std::clog を介して行う場合はフラッシュしない。

#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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 455 C++98 std :: cerr . tie ( ) および
std :: wcerr . tie ( ) がヌルポインタを返していた
それぞれ & std:: cout および
& std:: wcout を返す

関連項目

標準ストリームオブジェクトを初期化する
( std::ios_base のpublicメンバークラス)
標準Cエラーストリームへの書き込み stderr
(グローバルオブジェクト)
標準C出力ストリームへの書き込み stdout
(グローバルオブジェクト)
入力ストリームに関連付けられた FILE * 型の式
出力ストリームに関連付けられた FILE * 型の式
エラー出力ストリームに関連付けられた FILE * 型の式
(マクロ定数)