【问题标题】:std::ofstream == NULL won't compile for -std=gnu++11, any workaround?std::ofstream == NULL 不会为 -std=gnu++11 编译,有什么解决方法吗?
【发布时间】:2015-12-11 21:24:58
【问题描述】:

考虑以下代码:

std::ostream file;
if( file == NULL ) std::cout << "Failed to open file" << std::endl;

在传递 -std=gnu11(GCC 5.2 的默认值)或仅使用
gcc code.cpp -o a.out 时,它可以完美编译。

-std=gnu++11 失败,但是:

no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’)`

最简单的解决方法是什么?

详情:

我必须使用 std=gnu++11 才能访问shared_ptr 定义。此外,我的一些代码是自动生成的,修改生成器需要付出合理的努力——所以我想知道是否有人能想出更简单的方法来摆脱这种“缺乏兼容性”。

【问题讨论】:

  • if (!file) std::cout &lt;&lt; "Failed.";
  • -std=gnu11 是一个 c 标志
  • if( file == nullptr )
  • @SergeRogatch 查看我的回答;这在 C++11 中发生了变化。
  • @SergeRogatch 即使合法,将对象与指针进行比较有什么意义?投射到bool 有点不同,也更有意义。

标签: c++ c++11 gcc stl


【解决方案1】:

首先编译它的唯一原因是因为std::iosofstream 派生自,在 C++11 之前提供了一个非显式(!)operator void*。从 C++11 开始,改为提供 explicit operator bool,它不允许您的代码需要的隐式转换。相反,写

if (!file) std::cout << "Failed to open file" << std::endl;

【讨论】:

  • 这非常有用。我想知道是否会在 GCC 命令行中放置某种标志或定义,以使丢失的“operator==”再次可见,这样我就不必遍历所有的源代码了代码。
  • 我认为代码一开始就是“错误的”。 ofstream 不是指针(当然,它可以转换为指针),因此不应将其视为指针。
  • 另外,由于它可以隐式转换为 bool,你可以编写像 int foo = file; 这样糟糕的东西,它会很高兴地编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2015-07-23
  • 2015-01-04
  • 2021-10-08
  • 2015-04-30
相关资源
最近更新 更多