Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard no-op output stream

Tags:

c++

iostream

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

For example :

std::ostream dummyStream(...); dummyStream << "Nothing will be printed"; 

I could just create an ostringstream, but data will be buffered (and I really don't want to make anything with them, so it adds a useless overhead).

Any idea ?

[edit] Found this related question which suits my needs. However, I think it could be useful to have a answer saying how to create a valid (no badbit) output stream with standard c++.

like image 887
Maël Nison Avatar asked Aug 06 '12 10:08

Maël Nison


People also ask

What is STD ostream in C++?

The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc.. Example: CPP14.

What library is ostream in?

C++ Library - <ostream>


2 Answers

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.

like image 89
john Avatar answered Sep 24 '22 14:09

john


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.

like image 25
jxh Avatar answered Sep 24 '22 14:09

jxh