Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between std::endl and '\n' for streambuffer implementations

I'm currently trying to implement a subclass of stringbuf to allow the buffer to tokenize for specific chars ('\n' in my case) and undertake an action if this char occurs (dump the message to a logger and clear buffer afterwards in my case). To achieve this goal, I overrode sputc (to implement watching out for the '\n') and xsputn (to use sputc indeed, as the GCC implementation doesn't seem to do this by default). For debugging purposes, I let sputc write out each character that is passed to it to stdout.

Now this is my question: If I use something like

mystream << "Some text" << std::endl;

sputc receives each character except of the '\n' which should be inducted by std::endl, so the action that is expected is not done because the '\n' isn't passed on. If I use something like

mystream << "Some text" << '\n';

or even

mystream << "Some text" << "\n" << std::flush;

everything works as expected and my sputc implementation gets the '\n' char.

So my question is: Shouldn't both code lines do exactly the same concerning the stringbuf behind, and if not, which other methods do I have to override to get the '\n'?

like image 970
crispinus Avatar asked Jun 13 '11 13:06

crispinus


People also ask

Why is std :: endl slow?

Endl is actually slower because it forces a flush, which actually unnecessary. You would need to force a flush right before prompting the user for input from cin, but not when writing a million lines of output.

Should you use Endl STD?

Use std::endl If you want to force an immediate flush to the output. Use \n if you are worried about performance (which is probably not the case if you are using the << operator).

Does n flush the buffer?

Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not.


1 Answers

You can't override sputc because sputc is not virtual. You need to overload overflow and sync and examine the whole pending sequence for occurrences of \n.

You shouldn't really need to overload xsputn unless you can do something optimal because you know something special about the device that backs your stream type.

like image 90
CB Bailey Avatar answered Sep 19 '22 23:09

CB Bailey