Question

This is a sample C++ code

ostream& log = cout;
ostream& getLog() { return log; }

// somewhere in code
getLog() << "Message";

When this code executes, the "Message" gets printed.

Q: What is the easiest way to discard those messages (don't print them, don't save them)? getLog must still be used by clients, but could return some mocked output stream that swallows all messages...

Was it helpful?

Solution

You could do the following horror:

ostream nullstream(0);
ostream& log = nullstream;

Passing null to the constructor of ostream will set the badbit flag and therefore discard all writes.

OTHER TIPS

There is a similar post that attempts to do this - the cpp way to emulate redirecting to /dev/null

Is it easy to implement one?

Yes. Derive a class from std::streambuf and override the protected virtual function overflow as follows

int overflow(int c) { return c; }

Then you can use a standard istream and set its stream buffer to an instance of your streambuf class using rdbuf. Or you can define your own derived ostream class which automatically uses an an instance of your streambuf class.

Quick an dirty:

Define a class that derive from std::ostream and that implements the << operator for whatever T doing nothing.

Unfortunately this may not work in some cases: the << operator in std::ostream isn't polymorphic (not virtual), hence your overridden << will be called only when the stream type is yourstream& and not std::ostream&.

More polite:

derive std::streambuf, with a class that has no buffer, and that overrides overlflow by always return 0.

Then create an std::ostream associated with that buffer, and return it from your getLog();

This will let ostream to play its job: convert values into text and send characters to the buffer. The buffer will just eat them without doing anything.

Polite for the library, not so efficient, being the ostream value-to-text routines called in any case.

The most efficient:

is make the compilation of logging statements conditinal: like

#ifdef DEBUG
#define DBG(x) x
#else
#define DBG(x)
#endif

// Your entire code here

#undef DBG

and write logging as

DBG(std::cout << logging_variables_and_text << std::endl);

When DEBUG is not defined, everything in DBG will be wiped out (and no CPU cycles will be anymore spent)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top