c++ - clang with -Weverything 标志没有捕获 vector 中不存在的元素

标签 c++ vector clang clang++ llvm-clang

我正在从 Stroustrup 的《使用 C++ 编程原则和实践》(第 2 版)一书中学习 C++。

以下代码片段:

#include "include/std_lib_facilities.h"

int main() {
  vector<int> v = { 5, 7, 9, 4, 6, 8 };
  vector<string> philosopher = { "Kant", "Plato", "Hume", "Kierkegaard" };

  philosopher[2] = 99; // compile-time error should be here, too
  v[2] = "Hume";       // compile-time error presented here as it should

  vector<int> vi(6);
  vector<string> vs(4);

  vi[20000] = 44; // run-time error, but not compile-time error
  cout << "vi.size() == " << vi.size() << '\n';

  return 0;
}

只给出这个编译时错误:

clang++ -std=c++1z -g -Weverything -Werror -Wno-c++98-compat -Wno-c++98-compat-pedantic -Ofast -march=native -ffast-math src/055_vector.cpp -o bin/055_vector
src/055_vector.cpp:11:7: error: assigning to 'int' from incompatible type 'const char [5]'
        v[2] = "Hume";           // compile-time error presented here as it should
             ^ ~~~~~~
1 error generated.

我使用 -std=c++1z -g -Weverything -Werror -Wno-c++98-compat -Wno-c++98-compat-pedantic 命令启用了错误检查。但是正如您所看到的,这些行没有给出错误,但根据本书,这些也应该像 v[2] = "Hume"; 一样:

philosopher[2] = 99;
vi[20000] = 44;

如果我从第一个控制台输出中注释掉 v[2] = "Hume"; 错误行并且我只使用 vi[20000] = 44; 行,更糟糕的是,它编译没有问题,但是在我尝试运行程序之后:

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'Range_error'
  what():  Range error: 20000

如何捕获 vector 中不存在的元素,以及如果我尝试将字符串分配给 vector 中的整数?看起来像 -Weverything 不包括这个。

在 clang 中是否有针对这种情况的更严格的隐藏标志,这些标志未包含在 -Weverything 下?

最佳答案

philosopher[2] = 99; 是合法的代码,它使字符串成为 1 个字符的字符串,字符的代码为 99。(可能是 'c' ).这似乎不直观,但 std::string 是几十年前设计的,现在如果不破坏现有代码就无法更改。

该标准没有为 vi[20000] = 44; 指定任何必需的诊断。这是运行时未定义的行为;如果执行从未到达该行,则不会出错。

要捕获运行时错误,有一些选项,例如在调试器中运行,或使用 clang 的地址清理器或 valgrind。

关于c++ - clang with -Weverything 标志没有捕获 vector 中不存在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297145/

相关文章:

c++ - 考虑引用和 const 的可变参数函数包装器

c++ - Windows 和 Linux 的 C++ Qt 头文件是否相同?

c++ - 在 C++ 中找到立方根?

c++ - 删除 vector 中的指针时出错

c++ - Clang 的写法中的 "annotated fallthrough"和 "partly annotated method"是什么?

clang 问题 : inline function inside another function body in C

xcode - 如何在 Xcode 中禁用一个文件的优化

c++ - 编写一个函数的原型(prototype),该函数需要一个正好是 16 个整数的数组

c++ - NxN 行列式函数 (C++) 的代码问题

c++ - 如何直接访问一个类的 vector 数据成员并打印出来?