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 同理)意味着发送到这些流对象的任何输出都会立即刷新至操作系统(通过 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 * 类型表达式
(宏常量)