c++ - 不抛出 std::out_of_range 异常

标签 c++ exception std stdvector

   // 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/

相关文章:

c++ - 需要一个 Qt 解决方法来将一个基础转换为另一个基础

java - 使用 cipher.getInstance 方法时出现 NoSuchAlgorithm 异常

java - 链接异常,捕获异常并抛出新异常

c++ - 如何制作 std::weak_ptr 的 c++11 std::unordered_set

c++ - Visual Studio 2013 : error C2039: 'SetDefaultDllDirectories' : is not a member of '` global namespace''

c++ - 什么时候使用表达式的类型(不是类别)?

c++ - 分配结构包括指针

c# - 如何检查是否已抛出任何异常?

c++ - 最有可能使用什么方法来处理多个键以使用 STL 容器获取值?

c++ - 我可以使用 std::copy 将数据的位模式从整数 vector 复制到 unsigned char 数组吗