From cppreference.com
classsentry;An object of class basic_ostream::sentry is constructed in local scope at the beginning of each member function of
that performs output (both formatted and unformatted). Its constructor prepares the output stream: checks if the stream is already in a failed state, flushes the tie()'d output streams, and performs other implementation-defined tasks if necessary. Implementation-defined cleanup, as well as flushing of the output stream if necessary, is performed in the destructor, so that it is guaranteed to happen if exceptions are thrown during output.
Member functions
constructs the sentry object. All the preparation tasks are done here
(public member function)
finalizes the stream object after formatted output or after exception, if necessary
(public member function)operator=
the assignment operator is deleted
(public member function)checks if the preparation of the stream object was successful
(public member function)
std::basic_ostream::sentry::sentry
explicitsentry(std::basic_ostream<CharT,Traits>&os);Prepares the stream for formatted output.
If os.good() is false, returns. Otherwise, if os.tie() is not a null pointer, calls os.tie()->flush() to synchronize the output sequence with external streams. During preparation, the constructor may call setstate(failbit) (which may throw
).
If after preparation is completed, os.good()==true, then any subsequent calls to operatorbool will return true.
Parameters
os - output stream to prepare Exceptions
if the end of file condition occurs.
std::basic_ostream::sentry::~sentry
~sentry();If (os.flags()&std::ios_base::unitbuf)&&!std::uncaught_exception()&&os.good()) is true, calls os.rdbuf()->pubsync(). If that function returns -1, sets badbit in os.rdstate() without propagating an exception.
std::basic_ostream::sentry::operator bool
explicitoperatorbool()const;Checks whether the preparation of the output stream was successful.
Parameters
(none)
Return value
true if the preparation of the output stream was successful, false otherwise.
Example
Run this code
#include<iostream>#include<sstream>structFoo{charn[6];};std::ostream&operator<<(std::ostream&os,Foo&f){std::ostream::sentrys(os);if(s)os.write(f.n,5);returnos;}intmain(){Foof={"abcde"};std::cout<<f<<'\n';}Output:
abcde Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++98 the destructor might call os.flush(), which may throw exceptions the exception is not propagated
C++98 operatorbool was not declared const (it is const in the
) added const
C++98 if os sets unitbuf, the destructor would call os.flush(), which
is an
and creates another sentry object
(whose destructor then creates another sentry object and so on) calls
os.rdbuf()->pubsync()
in this case instead See also