The canonical way to read lines from a text file is:
std::fstream fs("/tmp/myfile.txt");
std::string line;
while (std::getline(line, fs)) {
doThingsWith(line);
}
(no, it is not while (!fs.eof()) { getline(line, fs); doThingsWith(line); }
!)
This works beacuse std::getline
returns the stream argument by reference, and because:
- in C++03, streams convert to
void*
, via anoperator void*() const
instd::basic_ios
, evaluating to the null pointer value when thefail
error flag is set;- see
[C++03: 27.4.4]
&[C++03: 27.4.4.3/1
]
- see
- in C++11, streams convert to
bool
, via anexplicit operator bool() const
instd::basic_ios
, evaluating tofalse
when thefail
error flag is set- see
[C++11: 27.5.5.1]
&[C++11: 27.5.5.4/1]
- see
In C++03 this mechanism means the following is possible:
std::cout << std::cout;
It correctly results in some arbitrary pointer value being output to the standard out stream.
However, despite operator void*() const
having been removed in C++11, this also compiles and runs for me in GCC 4.7.0 in C++11 mode.
How is this still possible in C++11? Is there some other mechanism at work that I'm unaware of? Or is it simply an implementation "oddity"?