clang以 - 所有的标志在矢量中没有不存在的元素

clang with -Weverything flag not catching nonexistent elements in vector

本文关键字:元素 不存在 标志 clang      更新时间:2023-10-16

我正在从Stroustrup的编程原理和使用C 的练习中学习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.

i启用了使用-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

如何在向量中捕获不存在的元素,以及我是否试图将字符串分配给向量中的int?看起来-Weverything不包括此。

在clang中,这种情况是否有更严格的隐藏标志,而 -Weverything

philosopher[2] = 99;是法律代码,它使字符串为1个字符字符串,并且字符具有代码99.(可能是'c')。这似乎是不直觉的,但是std::string是数十年前设计的,现在它在不破坏现有代码的情况下无法更改。

该标准未为vi[20000] = 44;指定任何必需的诊断。这是运行时不确定的行为;如果执行未达到该线路,那将不是错误。

要捕获运行时 - 有一些选项,例如在调试器中运行,或使用Clang的地址消毒剂或Valgrind。