C ++ Ifstream对象等于nullptr,但它不是一个指针? [英] C++ Ifstream object equals nullptr but it isn't a pointer?

查看:479
本文介绍了C ++ Ifstream对象等于nullptr,但它不是一个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ifstream 打开文件失败的测试程序。代码如下: -

I was trying a test program on failures of opening a file using ifstream. The code is below :-

#include <iostream>
#include <fstream>
#include <type_traits>
using namespace std;
int main()
{
    ifstream ifs ("wrong_filename.txt");
    cout << boolalpha;
    cout << is_pointer<decltype(ifs)>::value <<"\n";
    cout << (ifs==nullptr);
    return 0;
}

输出为: -

false
true

c $ c> ifs 不是指针,那么它如何等于 nullptr

If ifs is not a pointer, then how does it equal to nullptr?

推荐答案

在C ++ 11之前,C ++流可隐式转换为 void * 。如果流不是无错状态,则结果将是 NULL ,如果是,则结果为其他。所以 ifs == NULL (不应该使用 nullptr ,见下文)将找到并使用该转换,

Until C++11, C++ streams are implicitly convertible to void*. The result will be NULL if the stream is not in an errorless state and something else if it is. So ifs == NULL (should not work with nullptr, see below) will find and use that conversion, and since your filename was wrong, the comparison will yield true.

在C ++ 11中,这被更改为显式转换为 bool false 表示错误, true void * 转换允许太多无意义的代码,例如您的示例。事实上,C ++ 11或C ++ 14模式下的当前编译器将会拒绝您的代码段, live 。因为你的代码显然至少是C ++ 11,你的编译器不接受它。

In C++11, this was changed to an explicit conversion to bool, with false indicating an error and true a good stream, because the void* conversion allowed too much nonsensical code, such as your example. Indeed, a current compiler in C++11 or C++14 mode will reject your snippet, live. Since your code is obviously at least C++11, your compiler is non-conforming by accepting it.

这些转换允许并且用于错误检查,如: / p>

Those conversions allow and are intended for error checks like this:

if ( !(ifs >> data) )
    std::cout << "Reading data failed.";

或类似于您的示例:

std::ifstream ifs ("wrong_filename.txt");
if (!ifs)
    std::cout << "Could not open file.";






有趣的事实:这可以干净地循环一个文件,例如:


Fun fact of the day: You can also use this to cleanly loop over a file, e.g.:

for (std::string line; std::getline(ifs, line);) {
    // Process line
}

这篇关于C ++ Ifstream对象等于nullptr,但它不是一个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆