【问题标题】:Why did this C++ program fail in compilation?为什么这个 C++ 程序编译失败?
【发布时间】:2025-12-04 10:00:01
【问题描述】:

我正在阅读this。我在支持C++11 的代码块 13.12 IDE 上测试了这个程序,但它在编译和编译器中出现了多个错误。看节目。它在在线编译器上运行良好,请参阅this

// bad_array_new_length example
#include <iostream>     // std::cout
#include <exception>    // std::exception
#include <new>          // std::bad_array_new_length

int main() {
  try {
    int* p = new int[-1];
  } catch (std::bad_array_new_length& e) {
    std::cerr << "bad_array_new_length caught: " << e.what() << '\n';
  } catch (std::exception& e) {   // older compilers may throw other exceptions:
    std::cerr << "some other standard exception caught: " << e.what() << '\n';
  }
}

编译器错误:

7   12      [Error] expected type-specifier

7   37      [Error] expected unqualified-id before '&' token

7   37      [Error] expected ')' before '&' token

7   37      [Error] expected '{' before '&' token

7   39      [Error] 'e' was not declared in this scope

7   40      [Error] expected ';' before ')' token

9   5       [Error] expected primary-expression before 'catch'

9   5       [Error] expected ';' before 'catch'

这里出了什么问题?是编译器错误还是代码块 13.12 IDE 不完全支持 C++11

请帮帮我。

【问题讨论】:

  • 您是否启用 C++11? GCC C++ 编译器通常需要一个特殊的标志 (-std=c++11)。
  • @为什么对这个问题投反对票?是什么原因?
  • 那么 Code::Blocks 使用什么编译器呢?什么版本的?
  • GCC 直到 4.9 版才真正获得完整的 C++11 功能,可能是您的版本不支持该异常。
  • 为什么对这个问题投反对票?这个问题有什么问题?

标签: c++ c++11 exception-handling compiler-errors


【解决方案1】:

您的编译器不支持std::bad_array_new_length

code blocks 13.12 的最高 Google 结果显示:

codeblocks-13.12mingw-setup.exe 文件包括来自 TDM-GCC(版本 4.7.1,32 位)的 GCC 编译器和 GDB 调试器。

GCC 4.7.1 was released in 2012。根据this mailing list post 的说法,即使是 trunk GCC 自 2013 年以来也只支持std::bad_array_new_length

通过将 GCC 参考手册一分为二,我们可以确定 GCC 4.8.4 doesn't have itGCC 4.9.2 does。您链接到的“在线编译器”运行 GCC 4.9.2。

长话短说,您将需要更新的 GCC。

“C++11 支持”是一个非常宽泛的术语,您会发现,直到最近,它基本上从未意味着完全C++11 支持.例如,C++11 regexes weren't supported at all until GCC 4.9

【讨论】:

  • 我安装了 mingw/gcc 4.9.2 但它没有std::bad_array_new_length(或std::to_string)。问题似乎出在 libstdc++ 的 Windows 端口上,而不是 g++ 本身。可能涉及到一些政治因素。
  • @MattMcNabb:很有趣。在这种情况下,问题在于 Windows 端口旧的 GCC 版本。
【解决方案2】:

如果您确实在使用 gcc 4.7.1(从your comment 可以理解)查看GCC 4.7.1 Standard C++ Library Reference Manual,您可以看到根据api doc,您的gcc 版本没有@987654324 @类。

【讨论】: