2

It's a well known fact that cout is unbuferred in VS2010 (see the post by Stephan Lavavej here). How come in the code below I can construct ostream hexout using cout's buffer ?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    // Construct ostream hexout with cout's buffer and setup hexout to print hexadecimal numbers

    ostream hexout(cout.rdbuf());
    hexout.setf (ios::hex, ios::basefield);
    hexout.setf (ios::showbase);

    // Switch between decimal and hexadecimal output using the common buffer

    hexout << "hexout: " << 32 << " ";
    cout << "cout: " << 32 << " ";
    hexout << "hexout: " << -1 << " " ;
    cout << "cout: " << -1 << " ";
    hexout << endl;
}
John Kalane
  • 1,163
  • 8
  • 17

2 Answers2

2

Every stream has a basic_streambuf associated with it. "Unbuffered" simply means that the basic_streambuf doesn't maintain an internal buffer (a chunk of memory) to buffer input/output, but instead it just reads/writes from/to the file (or console, etc) directly.

user1610015
  • 6,561
  • 2
  • 15
  • 18
  • If I understood you correctly, what you're saying is that `hexout` will share with `cout` its `streambuf` object, which doesn't have a memory buffer. Is that the idea ? – John Kalane Jan 26 '13 at 01:23
1

The buffering (or lack thereof) doesn't occur directly in the std::stream. It occurs in the std::streambuf that is contained in a std::stream. What a stream does is to translate content to some string representation and send that translated content to the stream buffer. Whether it sends it a byte at a time or in larger chunks is (I think) implementation defined.

Your code works because it's all in one thread. When everything is in one thread, the fact that you are using two streams that share a common stream buffer isn't a problem. The call to hexout.operator<< completes before the call to cout.operator<< starts. The semicolon is a sequence point.

Create two threads, one using hexout and the other cout, and you may well have a mess if you don't protect the writes with some kind of locking mechanism.

David Hammen
  • 32,454
  • 9
  • 60
  • 108