Is there a null std::ostream implementation in C++ or libraries?

If you have boost, then there's a null ostream & istream implementation available in boost/iostreams/device/null.hpp . The gist of it:

#include "boost/iostreams/stream.hpp"
#include "boost/iostreams/device/null.hpp"
...
boost::iostreams::stream< boost::iostreams::null_sink > nullOstream( ( boost::iostreams::null_sink() ) );
...

The simplest solution is just to use an unopened std::ofstream. This will result in an error state in the stream, but most outputters won't check this; the usual idiom is to leave the check to the end, after the close (which would put it in code you wrote, where you know that the stream should be invalid).

Otherwise, it's pretty straight forward to implement: just create a streambuf which contains a small buffer, and sets it up in overflow (always returning success). Note that this will be slower than the unopened file, however; the various >> operators will still to all of the conversion (which they don't do if the stream has an error state).

EDIT:

class NulStreambuf : public std::streambuf
{
    char                dummyBuffer[ 64 ];
protected:
    virtual int         overflow( int c ) 
    {
        setp( dummyBuffer, dummyBuffer + sizeof( dummyBuffer ) );
        return (c == traits_type::eof()) ? '\0' : c;
    }
};

It's usual to provide a convenience class derived from istream or ostream as well, which will contain an instance of this buffer which it uses. Something along the lines of:

class NulOStream : private NulStreambuf, public std::ostream
{
public:
    NulOStream() : std::ostream( this ) {}
    NulStreambuf* rdbuf() const { return this; }
};

Or you can just use an std::ostream, passing the address of the streambuf to it.


If you set badbit on a stream it won't output anything:

#include <iostream>

int main() {
    std::cout << "a\n";

    std::cout.setstate(std::ios_base::badbit);
    std::cout << "b\n";

    std::cout.clear();
    std::cout << "c\n";
}

Outputs:

a
c

Tags:

C++

Null

Ostream