// The following code works fine, throwing a std::out_of_range exception:
std::vector<double> vd{ 1.5 };
try {
int i{ -1 };
double d = vd.at(i); // exception is thrown
}
catch (std::out_of_range& re) {
std::cout << "Exception is " << re.what() << std::endl; // invalid vector subscript
}
如果我使用无效索引访问 for 循环中的 vector 元素,则没有 std::exception
虽然我使用 .at()
被抛出.为什么是std::out_of_range
没有抛出异常?// in a for loop, this does not throw the exception!
std::vector<double> vd{ 1.5 };
try {
for (int i = -1; i < vd.size(); ++i)
double d = vd.at(i); // exception is not thrown. Why?
}
catch (std::out_of_range& re) {
std::cout << "Exception is " << re.what() << std::endl; // exception is not thrown
}
最佳答案
因为循环不执行。 -1 < vd.size()
是假的。size()
返回 未签名 值(value)。所以在比较两个数字之前-1
转换为无符号值。此转换是对最大 unsigned
取模完成的值加一,即 -1
转换为可能的最大 unsigned
值(value)。然后将其与 vector 的大小进行比较,这种比较总是错误的。
由于这个原因,有符号/无符号比较是有问题的。尽管定义明确,但如果带符号值为负,则它们不会以数学上预期的方式工作。你的编译器应该警告你这个问题。
关于c++ - 不抛出 std::out_of_range 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64884080/