Namespaces
Variants
Views
Actions

std::basic_ostream::sentry

From cppreference.com
< cpp‎ | io‎ | basic ostream
Revision as of 14:48, 4 June 2013 by P12 (Talk | contribs)

Defined in header <ostream>
template< class CharT, class Traits = std::char_traits<CharT> >
class std::basic_istream<CharT,traits>::sentry

An object of class basic_ostream::sentry is constructed in local scope at the beginning of each member function of std::basic_ostream 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.

Contents

Member functions

(constructor)
constructs the sentry object. All the preparation tasks are done here
(public member function) [edit]
(destructor)
finalizes the stream object after formatted output or after exception, if necessary
(public member function)
operator=
the assignment operator is deleted
(public member function)
operator bool
checks if the preparation of the stream object was successful
(public member function) [edit]

std::basic_ostream::sentry::sentry

explicit sentry(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 std::ios_base::failure.

If after preparation is completed, is.good() == true, then any subsequent calls to operator bool will return true.

Parameters

os - output stream to prepare

Exceptions

std::ios_base::failure if the end of file condition occurs.


std::basic_ostream::sentry::~sentry

~sentry();

Does nothing.


std::basic_ostream::sentry::operator bool

explicit operator bool() 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

#include <iostream>
#include <sstream>
 
struct Foo {
    char n[5];
};
 
std::ostream& operator<<(std::ostream& is, Foo& f)
{
    std::ostream::sentry s(is);
    if (s) {
        is.write(f.n, 5);
    }
    return is;
}
 
int main()
{
    Foo f = { 'a', 'b', 'c', 'd', 'e' };
    std::cout << f << '\n';
}

Output:

abcde

See also

inserts formatted data
(public member function) [edit]