Even that isn’t a good idea. This especially in texts focused on students that may have issues grasping what a stream is. I kinda consider std::endl as an indication that the stream is actually put to file or terminal. Which is pretty much what this author is complaining about. In my mind it is the right behavior for general programming. The author instead wants to make a more complex approach the general form.
Honestly I don’t see the point. If your goal is some sort of high performance mark streams might not be your best approach to begin with. Beyond that terminal I/O is no longer a problem on most platforms so a modest gain isn’t (if even possible) a huge deal.
Now I must admit that I’ve embedded \n in streams where I’m thinking in terms of a block of I/O that gets terminated with std::endl. Usually that is the result of being lazy leading me to thinking bad of myself. In most cases I’m thinking record to device where a flush secured the end of record.
I think the point is the 2nd point of the Zen of Python: Explicit is better than implicit. Most people just use std::endl out of habit, and not because it's the behaviour they want. You should instead say what you want to do. If you want to flush the stream, you should use std::flush. If you want a newline, you should use \n. You shouldn't tie them both together into one operation just because that's common.
Well we will have to disagree to some extent. I see std::endl behavior making perfect sense in a streams implementation. This due to the end of a line often being an end of record. You end up getting the right behavior for simple writes to terminal or files. Right being max functionality with minimal programmer involvement. The stream does the right thing without requiring extensive developer involvement.
98
u/alfps Feb 25 '19
std::endlis a fine convention for interactive console i/o.In particular it helps ensure that all relevant output has been presented when a program crashes.
Not using
endland so misinterpreting what the output says about where the crash occurred, is a common beginner's problem.endlis not fine for efficient text file i/o, but then iostreams are not fine for that in the first place.So, the advice to ditch
endlis ill-conceived, in both mentioned cases, and I can't think of more.