Standard no-op output stream

The basic method voor new stream classes is:

  1. Derive a class from std::streambuf;
  2. Override the virtual functions in that class. This is where the real work is done. In your case, empty implementations should be good enough.
  3. Derive a class from std::ostream with one member, your streambuf class.
  4. The constructor of your streamclass should forward the pointer to that member to the base constructor of std::ostream.

I'm afraid you won't get rid of the formatting step, though.

Hopefully this gives you some pointers; I don't have the time to expand this into a full answer, sorry.

Update: See john's answer for details.


If this is to disable logging output, your dummyStream would still cause arguments to be evaluated. If you want to minimize impact when logging is disabled, you can rely on a conditional, such as:

#define debugStream \
    if (debug_disabled) {} \
    else std::cerr

So if you have code like:

debugStream << "debugging output: " << foo() << std::endl;

No arguments will be evaluated if debug_disabled is true.


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.

Tags:

C++

Iostream