std::cerr, std::wcerr
The global objects std::cerr and std::wcerr control output to a stream buffer of implementation-defined type (derived from std::streambuf and std::wstreambuf , respectively), associated with the standard C error output stream stderr .
These objects are guaranteed to be initialized during or before the first time an object of type std::ios_base::Init is constructed and are available for use in the constructors and destructors of static objects with ordered initialization (as long as <iostream> is included before the object is defined).
Unless std::ios_base::sync_with_stdio(false) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output.
Once initialized, (std::cerr.flags() & unitbuf) != 0 (same for wcerr ) meaning that any output sent to these stream objects is immediately flushed to the OS (via std::basic_ostream::sentry ‘s destructor).
In addition, std::cerr.tie() returns & std:: cout (same for wcerr and std::wcout ), meaning that any output operation on std::cerr first executes std:: cout . flush ( ) (via std::basic_ostream::sentry ‘s constructor) (since C++11) .
Notes
The ‘c’ in the name refers to «character» (stroustrup.com FAQ); cerr means «character error (stream)» and wcerr means «wide character error (stream)».
Example
output to stderr via std::cerr flushes out the pending output on std::cout , while output to stderr via std::clog does not.
std::cerr, std::wcerr
Глобальные объекты 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 (то же самое для wcerr ), что означает, что любой вывод, отправленный этим объектам потока, немедленно сбрасывается в ОС (через std::basic_ostream::sentry ). ).
Кроме того, std::cerr.tie() возвращает &std::cout (то же самое для wcerr и std::wcout ), что означает, что любая операция вывода на std::cerr сначала выполняет std::cout.flush() (через std::basic_ostream::sentry ) (начиная с C++11).
Notes
Буква «c» в названии означает «персонаж» ( stroustrup.com FAQ ); cerr означает «ошибка символа (поток)», а wcerr означает «ошибка широкого символа (поток)».
Example
вывод в stderr через std::cerr сбрасывает ожидающий вывод на std::cout , а вывод в stderr через std::clog — нет.
std:: cerr
Object of class ostream that represents the standard error stream oriented to narrow characters (of type char ). It corresponds to the C stream stderr .
The is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog ).
As an object of class ostream , characters can be written to it either as formatted data using the insertion operator ( operator<< ) or as unformatted data, using member functions such as write .
The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
In terms of static initialization order, cerr is guaranteed to be properly constructed and initialized no later than the first time an object of type ios_base::Init is constructed.
cerr is not tied to any other output stream (see ios::tie ).
In terms of static initialization order, cerr is guaranteed to be properly constructed and initialized no later than the first time an object of type ios_base::Init is constructed, with the inclusion of <iostream> counting as at least one initialization of such objects with static duration.
cerr is tied to the standard output stream cout (see ios::tie ), which indicates that cout ‘s buffer is flushed (see ostream::flush ) before each i/o operation performed on cerr .
By default, cerr is synchronized with stderr (see ios_base::sync_with_stdio ).
A program should not mix output operations on cerr with output operations on wcerr or wclog (or with other wide-oriented output operations on stderr ): Once an output operation has been performed on either, the standard error stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stderr .
For more information on the operations supported by cerr , see the reference for its type: ostream .
Объект cerr в C++
Объект cerr в C++ – это объект класса ostream. Он связан со стандартным потоком вывода ошибок C stderr.
Декларация
Он определен в заголовочном файле <iostream>.
Гарантируется, что объект cerr в С++ будет инициализирован во время или до первого создания объекта типа ios_base :: Init. После создания объекта cerr выражение (cerr.flags unitbuf) не равно нулю, что означает, что любой вывод, отправленный этим объектам потока, немедленно сбрасывается в операционную систему. Также cerr.tie() == cout, т.е. cerr.tie() возвращает cout, что означает, что cout.flush() выполняется перед любой операцией вывода на cerr.
«C» в cerr означает «символ», а «err» означает «ошибку», следовательно, cerr означает «символьную ошибку».
Объект cerr используется вместе с оператором вставки (<<) для отображения потока символов. Общий синтаксис:
Оператор извлечения может использоваться более одного раза с комбинацией переменных, строк и манипуляторов (например, endl):
Начинающие программисты на используют cout C++ для отображения ошибки, используя стандартный вывод для отладки своих программ, но всегда полезно использовать cerr для отображения ошибок.
Это связано с тем, что вместо того, чтобы отображать поток ошибок на экране, вы можете позже изменить поток ошибок, чтобы записать ошибки в файл.
Пример: как работает cerr?
Когда вы запустите программу, вывод будет: [если файл не может быть открыт]