C ++或库中是否存在std :: ostream实现?

我正在寻找一个像/dev/null一样的std::ostream实现。 它会忽略任何stream式传输给它的东西。 标准库或Boost中是否存在这样的事情? 或者我必须推出自己的?

如果你有提升,那么在boost / iostreams / device / null.hpp中有一个空的ostream&istream实现。 它的要点:

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

最简单的解决scheme就是使用未打开的std::ofstream 。 这将导致stream中的错误状态,但大多数输出​​不会检查这个; 通常的习惯用法是在closures之后将检查结束(这会将其写入代码中,您知道该stream应该是无效的)。

否则,实现起来非常简单:创build一个包含一个小缓冲区的streambuf ,并将其设置为overflow (总是返回成功)。 请注意,这将比未打开的文件慢, 各种>>运算符仍然会进行所有的转换(如果stream有错误状态,他们不会这样做)。

编辑:

 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; } }; 

通常提供一个从istreamostream派生的便利类,它将包含它使用的这个缓冲区的一个实例。 有些东西是:

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

或者你可以使用std::ostream ,将streambuf的地址传递给它。

如果你在stream上设置badbit ,它将不会输出任何东西:

 #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"; } 

输出:

 a c 

我知道这是非常古老的线程,但我想添加到任何人正在寻找相同的解决scheme没有提升和最快的一个。

我把上面三个不同的提议结合起来,一个直接写到/ dev / null(所以涉及内核)。

令人惊讶的是获得最多选票的NullStreamperformance最差。

这里是100,000,000写道的结果:

 a) /dev/null : 30 seconds b) NullStream: 50 seconds c) badbit : 16 seconds (the winner in speed, but cannot test for errors!) d) boost : 25 seconds (the ultimate winner) 

这是testing代码

 #include <iostream> #include <fstream> #include <time.h> #include <boost/iostreams/stream.hpp> class NullStream : public std::ostream { class NullBuffer : public std::streambuf { public: int overflow( int c ) { return c; } } m_nb; public: NullStream() : std::ostream( &m_nb ) {} }; int test( std::ostream& ofs, const char* who ) { const time_t t = time(NULL); for ( int i = 0 ; i < 1000000000 ; i++ ) ofs << "Say the same" ; std::cout << who << ": " << time(NULL) - t << std::endl; } void devnull() { std::ofstream ofs; ofs.open( "/dev/null", std::ofstream::out | std::ofstream::app ); test(ofs, __FUNCTION__); ofs.close(); } void nullstream() { NullStream ofs; test(ofs, __FUNCTION__); } void badbit() { std::ofstream ofs; ofs.setstate(std::ios_base::badbit); test(ofs, __FUNCTION__); } void boostnull() { boost::iostreams::stream< boost::iostreams::null_sink > nullOstream( ( boost::iostreams::null_sink() ) ); test(nullOstream, __FUNCTION__); } int main() { devnull(); nullstream(); badbit(); boostnull(); return 0; } 

编辑

最快的解决scheme – 我们使用badbit – 有一个缺点。 如果程序检查输出是否成功写入 – 我不知道为什么程序不应该这样做 – 那么就会因为这个坏处而失败。 因此,亚军 – 博斯特 – 是赢家。