不理解 cplusplus.com istream::read 的示例

Don't understand cplusplus.com example for istream::read

上cplusplus.com给出了一个例子:

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    // ...buffer contains the entire file...

    delete[] buffer;
  }
  return 0;
}

谁能解释一下为什么最后的if (is)可以判断是否读完所有字符?这与我们已经使用的 if 语句以及我解释它的方式(可能过于简单和错误)是一样的,我们只检查它是否存在,但这不是已经建立了吗?

std::ifstream 定义了 operator bool() const,它将流隐式转换为布尔值。

来自 cplusplus.com on operator bool():

Returns whether an error flag is set (either failbit or badbit).

Notice that this function does not return the same as member good, but the opposite of member fail.

http://www.cplusplus.com/reference/ios/ios/operator_bool/

std::ifstream 有一个到 bool 的转换运算符,returns 无论是否在流上设置了 badbitfailbit

if (!is.fail()) {/*...*/}.

本质上是shorthand