重置 ostream,C++
我有 2 个不同的 ostream,其中之一是 cerr,使用相同的流缓冲区,我有一些库可能以某种方式修改了 cerr,(标志?格式修饰符?)。
cerr.rdbuf(&mystreambuffer);
ostream teststream(&mystreambuffer);
cerr << "This " << " is " << " a " << " test";
teststream << "This " << " is " << " a teststream " << " test";
打印:
This
is
a
test
This is a teststream test
调试 mystreambuffer
我注意到 cerr 在每个 <<
操作中调用 mystreambuffer->sync()
而 teststream 不调用根本就是这样。
如果我是正确的 cerr
只是一个标准的 ostream,那么,为什么我会看到刷新时间的这种差异?如何将 cerr 重置回正常的刷新操作?
编辑:我看到你们在评论unitbuf并且它是cerr中的默认值,但是如果它是默认的,它不是也会在这里一步步写吗?
#include <iostream>
int main(){
std::cerr << "This " << " is " << " a cerr " << " test\n";
std::cout << "This " << " is " << " a cout " << " test\n";
}
Cobain /tmp$ ./test
This is a cerr test
This is a cout test
I have 2 different ostreams, one of them cerr, using the same streambuffer, I have some libraries in that might have modified cerr somehow,(flags? format modifiers?).
cerr.rdbuf(&mystreambuffer);
ostream teststream(&mystreambuffer);
cerr << "This " << " is " << " a " << " test";
teststream << "This " << " is " << " a teststream " << " test";
prints:
This
is
a
test
This is a teststream test
Debugging mystreambuffer
I've noticed that cerr calls mystreambuffer->sync()
every <<
operation while teststream does not call it at all.
If I am correct cerr
is just an standard ostream, then, why do I see this difference in flushing times? How can I reset cerr back to normal flushing operations?
EDIT: I see you guys are commenting about unitbuf and it being default in cerr, but if it was default, wouldn't it write step by step here as well?
#include <iostream>
int main(){
std::cerr << "This " << " is " << " a cerr " << " test\n";
std::cout << "This " << " is " << " a cout " << " test\n";
}
Cobain /tmp$ ./test
This is a cerr test
This is a cout test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试 std::cerr.unsetf( std::ios_base::unitbuf );。默认情况下,
cerr
会启用该标志。Try
std::cerr.unsetf( std::ios_base::unitbuf );
. That flag is on forcerr
by default.ios::unitbuf 标志是 cerr 设置为默认值的原因。
您需要使用 nounitbuf 操纵器来修复它。一些较旧的库可能没有它,如果有,则使用 unsetf。
编辑:
unitbuf 的默认设置取决于实现:)
ios::unitbuf flag is the reason for that which is set to default for cerr.
You need to use the nounitbuf manipulator in order to fix it. Some older libraries may not have it, if so then use unsetf.
Edit:
Default setting for unitbuf is implementation-dependent :)