clang以 - 所有的标志在矢量中没有不存在的元素
clang with -Weverything flag not catching nonexistent elements in vector
我正在从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。
相关文章:
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- g++ 说函数不存在,即使包含正确的标头
- 更新的矢量元素不打印
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- C++ 尝试在不存在的构造函数中引用已删除的函数(使用 rapidJson)
- 查找第一个数组中不存在的元素
- 查找不存在的键时,unordered_map返回什么
- 转置矩阵:交换元素不会更改值
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- set::find 查找不存在的元素
- 如果键不存在,使用 [] 运算符访问 STL Map 元素会添加新元素
- lower_bound 在 C++ STL 中返回迭代器,即使元素不存在也是如此.如何避免这种情况?
- 如果路径的每个元素不存在,请为其创建一个目录
- 在C++中传递结构数组 - 被调用函数中不存在结构元素,如何正确传递向量?
- clang以 - 所有的标志在矢量中没有不存在的元素
- 有效地测试 QSet 是否包含元素,如果不存在,则插入
- 为什么 STL 向量的迭代器可以指向不存在的元素?
- 使用0来显示不存在元素的集合的子集
- 获取受不存在元素限制的QSet子集