cppannotations/yo/iostreams/coupling.yo
2010-11-06 15:47:24 +00:00

19 lines
1.2 KiB
Text

Ostream objects hi(ostream coupling) can be em(coupled) to ti(ios) objects
using the ti(tie) member function. Tying results in flushing the tt(ostream)'s
buffer whenever an i(input) or i(output) operation is performed on the tt(ios)
object to which the tt(ostream) object is tied. By default ti(cout) is tied
to ti(cin) (using tt(cin.tie(cout))). This tie means that whenever an
operation on tt(cin) is requested, tt(cout) is flushed first. To break the
tie, tt(ios::tie(0)) can be called. In the example: tt(cin.tie(0)).
Another useful coupling of streams is shown by the tie between ti(cerr) and
ti(cout). Because of the tie standard output and error messages written to the
screen are shown in sync with the time at which they were generated:
verbinclude(examples/tiecerrcout.cc)
An alternative way to couple streams is to make streams use a common
tt(streambuf) object. This can be implemented using the hi(rdbuf)
tt(ios::rdbuf(streambuf *)) member function. This way two streams can use,
e.g. their own formatting, one stream can be used for input, the other for
output, and redirection using the stream library rather than operating
system calls can be implemented. See the next sections for examples.