Vlad Nestorov
Vlad Nestorov

Reputation: 360

cin causing cout to flush, after I untied the two streams

I am trying to understand the behavior of iostreams with respect to tie(). From what I find, the below code should NOT output anything to the screen.

    cin.tie(NULL);
    int i;
    cout << "TEST";
    cin >> i;
    while (true);

Instead it should behave like

    cin.tie(NULL);
    int i;
    cout << "TEST";
    read(0, &i, sizeof(int));
    while (true);

In other words, cout buffer is getting flushed when cin input is invoked, even though the streams are untied. I have tried compiling this code with g++ 4.8.0 and 4.6.3. I have also tried calling cin.tie() after cin.tie(NULL) which correctly returns NULL, so the streams should not be tied.

Is there more to tie() that I'm missing?

Upvotes: 1

Views: 700

Answers (1)

Cubbi
Cubbi

Reputation: 47428

You didn't execute cout.sync_with_stdio(false);, so your std::cout is synchronized with C I/O, which means that every single output is individually and immediately sent over to a C I/O library call, and is then subject to the implementation-defined rules of glibc, in your case.

On a quick check, this glibc manual mentions that

...buffered output on a stream is flushed automatically:

  • Whenever an input operation on any stream actually reads data from its file.

(although it doesn't sound convincing since nothing was read from stdin yet.. in any case, cout.sync_with_stdio(false) makes this cin.tie(NULL) testcase behave as expected on my Linux).

Upvotes: 3

Related Questions