简体   繁体   中英

Resetting an ostream, C++

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

Try std::cerr.unsetf( std::ios_base::unitbuf ); . That flag is on for cerr by default.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM