Search code examples
c++buffercoutflush

When does the buffer flush


For cpp, I know that we have three cases to flush the buffer:

  1. When we get std::cin
  2. When we std::cout<<std::endl (or ohters things like endl)
  3. When we call some function like fflush

If I am right, there is a question:
If I just write std::cout<<"hello world"; in main and run it, I could see "hello world" at the console. So, by whom and when does the buffer flush? By the compiler? Or the buffer will flush when the main finishes?


Solution

  • You probably want to read about std::unitbuf and std::nounitbuf. Here's a decent reference.

    It might be helpful to play with some simple examples. For instance, the following code will not print Hello world ever, because there won't be automatic flushing of the output stream after any output operation:

    EXAMPLE 1

    #include<iostream>
    
    int main()
    {
        // ----- Don't want automatic flushing ------
        std::cout << std::nounitbuf;
        std::cout << "Hello world";
    
        while (1)
        {
            ;
        }
    }
    

    And this code example will indeed print Hello world, because I specified that I want the automatic flushing to be enabled:

    EXAMPLE 2

    #include<iostream>
    
    int main()
    {
        // ----- I do want automatic flushing ------
        std::cout << std::unitbuf;
        std::cout << "Hello world";
    
        while (1)
        {
            ;
        }
    }
    

    I know that the infiite while loop looks a bit silly, but it's the easiest and most portable way of pausing the code that I can think of right now (I'm sure there are better ways, though!). This way I don't get flushing because of (1) code termination, (2) destructors being called and (3) so on. It's all down to the properties of std::cout.