std::cerr, std::wcerr
来自 cppreference.cn
定义于头文件 <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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 455 | C++98 | std::cerr.tie() 和 std::wcerr.tie() 返回空指针 |
它们分别返回 &std::cout 和 &std::wcout |
[编辑] 参见
初始化标准流对象 ( std::ios_base 的公共成员类) | |
写入标准 C 错误流 stderr (全局对象) | |
写入标准 C 输出流 stdout (全局对象) | |
与输入流关联的 FILE* 类型的表达式 与输出流关联的 FILE* 类型的表达式 与错误输出流关联的 FILE* 类型的表达式 (宏常量) |