Is there a null std::ostream implementation in C++ or libraries?
我正在寻找一个类似于/dev/null的std::ostream实现。它只会忽略流向它的任何内容。标准库或Boost中是否存在这样的东西?还是我必须自己动手?
- 您可以将devnull打开为std::ofstream
-
需要便携式的东西,@ Alexandre
-
我想出了(否则这将是一个答案)stackoverflow.com/questions/313111/dev-null-in-windows应该涵盖足够的情况。
-
将nullptr传递给std :: ostream怎么样?
-
@Myon你不能那样做。
如果您有助推力,则ostream为空
-
@paperjam,能否请您详细说明?
-
@ user1229080 stackoverflow.com/questions/1424510/
最简单的解决方案是使用未打开的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。
-
最初的想法(未打开的std::ofstream)非常酷。它是否可靠/符合标准,并且将来不太可能引起问题(异常?)?我有点担心性能,但是我想唯一的浪费是调用<<运算符,检查一个if并返回?
-
@TomaszGandor:"它是否可靠/符合标准,并且将来不太可能引起问题(异常?)?"好吧,有时候..
如果在流上设置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\
";
} |
输出:
- @MatthieuM。使用std::cout << std::boolalpha也是对全局变量的修改。也使用std::cout << anything。我不明白你的意思。
-
尽管通常情况是正确的,但如果一个程序或两个程序中的一个或两个都更改了std::cout的配置,则它们之间会发生利益冲突。但是,为什么它是可配置的?如果过去,我将设计C,则将输出过滤与输出流分开,例如std::out_filter of; of << std::boolalpha << std::whatever_option; std::out_proxy(std::cout, of) <<"something";。
-
@Notinlist:关于ostream的设计,我有很多原因;那时是C早期,那里的全局变量仍然很普遍,几乎没有经验,这表明...我发现合并格式和在哪里输出变得很尴尬,例如,我发现注入格式化程序变得很尴尬而不是使用Decorator模式等等。但是我有事后见识。
n
-
我认为/ dev / null无法移植到Windows。我尝试了ofs.open("),它没有写任何文件,所以也许这是一个更好的选择?
-
@Eyal-我专注于/ dev / null,因为它是问题的对象。我相信Windows中没有nil,但从开发的angular来看我不知道如何使用它...
-
Windows上的" nul":stackoverflow.com/questions/313111/
n
n
-
很好但是请注意,仍然存在与badbit相同的问题:使用rdbuf时,如果流缓冲区是空指针,该函数会自动设置badbit错误状态标志(如果已将成员异常传递给badbit,则可能会引发异常)。 [cplusplus.com/reference/ios/ios/rdbuf/]
n
-
请编辑您的答案,并通过解释您的答案如何解决问题来添加一些上下文,而不是发布仅代码的答案。来自评论
-
我一直在尝试制定出这样的解决方案,以便优化程序可以消除非调试版本中的调试日志记录。不幸的是,此处显示的流插入运算符模板与std::endl之类的操纵器不匹配。
n
n