从文本文件中读取行的规范方法是:
std::fstream fs("/tmp/myfile.txt");
std::string line;
while (std::getline(line, fs)) {
doThingsWith(line);
}
(不,不是! while (!fs.eof()) { getline(line, fs); doThingsWith(line); })
这是有效的,因为std::getline通过引用返回流参数,并且因为:
- 在 C++03中,当设置错误标志
时,流
void*通过operator void*() constin转换为std::basic_ios空指针值;fail- 见
[C++03: 27.4.4]&[C++03: 27.4.4.3/1]
- 见
bool在 C++11 中,流通过explicit operator bool() constin转换为,在设置错误标志 时std::basic_ios评估为falsefail- 见
[C++11: 27.5.5.1]&[C++11: 27.5.5.4/1]
- 见
在 C++03 中,这种机制意味着以下是可能的:
std::cout << std::cout;
它正确地导致一些任意指针值被输出到标准输出流。
但是,尽管operator void*() const已在 C++11 中删除,但它也可以在 C++11 模式下的 GCC 4.7.0 中为我编译和运行。
这在 C++11 中怎么可能?还有其他一些我不知道的机制在起作用吗?或者它只是一个实现“奇怪”?