Standard no-op output stream

后端 未结 6 1832
余生分开走
余生分开走 2020-11-29 03:25

Is there a way to create an ostream instance which basically doesn\'t do anything ?

For example :

std::ostream dummyStream(...);
dummyStream <<         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 04:00

    You need a custom streambuf.

    class NullBuffer : public std::streambuf
    {
    public:
      int overflow(int c) { return c; }
    };
    

    You can then use this buffer in any ostream class

    NullBuffer null_buffer;
    std::ostream null_stream(&null_buffer);
    null_stream << "Nothing will be printed";
    

    streambuf::overflow is the function called when the buffer has to output data to the actual destination of the stream. The NullBuffer class above does nothing when overflow is called so any stream using it will not produce any output.

提交回复
热议问题