The simplest solution is to simply output to unopened std::ofstream (or any other output stream in an error state). This will cause the thread to be constantly in an error state. This may be an advantage ( << will skip formatting), but if there is any code that you cannot control error checking and does something specific, if you are likely to have problems.
Otherwise, it is quite simple to implement an empty stream; the only streambuf function you really need to override is overflow . Something like the following should do the trick:
class NulStreambuf : public std::streambuf { char dummyBuffer[64]; protected: virtual int overflow( int c ) { setp( dummyBuffer, dummyBuffer + sizeof( dummyBuffer ) ) ; return (c == EOF) ? '\0' : c ; } };
(The buffer will avoid unnecessary calls to virtual functions. Platforms, this is significant.)
Then create an output stream that uses it:
class NulOStream : public NulStreambuf, public std::ostream { public: NulOStream() : std::ostream( this ) {} };
(Using inheritance rather than restraint ensures that streambuf is completely designed before being transferred to ostream . In practice, this is not required at all, but the standard does not seem to allow the transfer of an streambuf to the ostream constructor.)
James kanze
source share