C++ 参考手册

位置:首页 > C++ 参考手册 >输入/输出库 > std::cerr, std::wcerr

定义于头文件 <iostream>
extern std::ostream cerr;
(1)
extern std::wostream wcerr;
(2)

全局对象 std::cerrstd::wcerr 控制到实现定义类型(分别导出自 std::streambufstd::wstreambuf )的流缓冲,与标准 C 错误输出流 stderr 关联。

保证这些对象在构造首个 std::ios_base::Init 类型对象之前或期间得到初始化,而且可用于带有序初始化的静态对象的构造函数和析构函数(只要在定义对象前包含 <iostream> )。

除非发布 sync_with_stdio(false) ,从多个线程为有格式和无格式输出访问这些对象是安全的。

一旦初始化,则 (std::cerr.flags() & unitbuf) != 0wcerr 也一样),这表示任何发送给这些流对象的输出都被立即冲入到 OS (通过 std::basic_ostream::sentry 的析构函数)。

另外, std::cerr.tie() 返回 &std::cout (对 wcerrwcout 相同),这表示任何 std::cerr 上的输出首先执行 std::cout.flush() (通过 std::basic_ostream::sentry 的构造函数)。(C++11 起)

注意

名称中的 'c' 指代“字符”( stroustrup.com FAQ ); cerr 表示“字符错误(流)”而 wcerr 表示“宽字符错误(流)”。

示例

通过 cerr 输出到 stderr ,冲入 cout 上的待处理输出,而通过 clog 输出到 stderr 不会。

#include <thread>
#include <iostream>
#include <chrono>
void f()
{
    std::cout << "Output from thread...";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "...thread calls flush()" << std::endl;
}
 
int main()
{
    std::thread t1(f);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::clog << "This output from main is not tie()'d to cout\n";
    std::cerr << "This output is tie()'d to cout\n";
    t1.join();
}

输出:

This output from main is not tie()'d to cout
Output from thread...This output is tie()'d to cout
...thread calls flush()

参阅

初始化标准流对象
(std::ios_base 的公开成员类)
写入到标准 C 错误流 stderr
(全局对象)
写入到标准 C 输出流 stdout
(全局对象)