The documentation for std::basic_ostream<CharT,Traits>::write
says [emphasis mine]:
Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, outputs the characters from successive locations in the character array whose first element is pointed to by s. Characters are inserted into the output sequence until one of the following occurs:
exactly count characters are inserted
inserting into the output sequence fails (in which case setstate(badbit) is called)
How am I to understand the statement in bold? What's this so-called "sentry object"?
As far as I can see, when std::basic_ostream<CharT,Traits>
is called there must already exist an instance whose type is std::basic_ostream
.
For example:
#include<iostream>
int main
{
std::string str{"thanks for your attention to this matter"};
std::cout.write(str.data(), str.length());
}
Notes: std::cout
's type is std::ostream
and std::ostream
is defined as typedef std::ostream std::basic_ostream<char>
.
CodePudding user response:
If you follow the UnformattedOutputFunction link in the text you quoted, you will find the following description of what the sentry is and what it does:
A UnformattedOutputFunction is a stream output function that performs the following:
Constructs an object of type
basic_ostream::sentry
with automatic storage duration, which performs the following
- if
eofbit
orbadbit
are set on the output stream, sets thefailbit
as well, and if exceptions onfailbit
are enabled in this output stream's exception mask, throwsios_base::failure
.- flushes the
tie()
'd output stream, if applicable.Checks the status of the sentry by calling
sentry::operator bool()
, which is equivalent tobasic_ios::good
.If the sentry returned
false
or sentry's constructor threw an exception, no output takes placeIf the sentry returned
true
, attempts to perform the desired output by inserting the characters into the output stream as if by callingrdbuf()->sputc()
orrdbuf()->xsputn()
. Additionally,rdbuf()->overflow()
andrdbuf()->sync()
may be called, but no other virtual member function ofstd::basic_streambuf
.
- if an exception is thrown during output, sets
badbit
in the output stream. If exceptions onbadbit
are enabled in this stream's exception mask, the exception is also rethrown.- If no exception was thrown, returns the value specified by the function.
In any event, whether terminating by exception or returning, the sentry's destructor is called before leaving this function.
Also, the documentation for FormattedOutputFunction (ie operator<<
) has a similar description for its use of the sentry
.
So, basically, every output method of ostream
constructs an instance of the nested ostream::sentry
class before performing the output work. The sentry
makes sure that the ostream
is in a valid state to accept output data. If it is not, the ostream
is put into a failure state, and an exception is thrown if needed.