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

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

我正在寻找一个类似于/dev/nullstd::ostream实现。它只会忽略流向它的任何内容。标准库或Boost中是否存在这样的东西?还是我必须自己动手?


如果您有助推力,则ostream为空


最简单的解决方案是使用未打开的std::ofstream。这个
将在流中导致错误状态,但大多数输出??器不会
检查一下;通常的习惯用法是在
关闭(将其放入您编写的代码中,您知道
流应该无效)。

否则,很容易实现:只需创建一个
streambuf包含一个小缓冲区,并在overflow中进行设置
(总是返回成功)。请注意,这将比
但是未打开的文件;各种>>运算符仍然适用于所有
转换(如果流具有错误状态,则不会执行此操作)。

编辑:

1
2
3
4
5
6
7
8
9
10
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;
    }
};

通常提供从istream派生的便利类
ostream以及其中的一个实例
它使用的缓冲区。类似于:

1
2
3
4
5
6
class NulOStream : private NulStreambuf, public std::ostream
{
public:
    NulOStream() : std::ostream( this ) {}
    NulStreambuf* rdbuf() const { return this; }
};

或者您也可以使用std::ostream传递地址
它的streambuf。


如果在流上设置badbit,则不会输出任何内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

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

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

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

输出:

1
2
a
c


n


n


n


n


n


n