std::out_of_range 没有抛出异常

std::out_of_range exception is not thrown

   // 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 循环中的向量元素,尽管我使用 .at(),但不会抛出 std::exception。为什么不抛出 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() returns 一个 无符号 值。所以在比较这两个数字之前 -1 被转换成一个无符号值。此转换以最大 unsigned 值加一为模完成,这意味着 -1 转换为可能的最大 unsigned 值。然后将其与向量的大小进行比较,并且该比较始终为假。

Signed/unsigned 由于这个原因,比较是有问题的。尽管定义明确,但如果带符号的值为负,它们将不会以数学预期的方式工作。你的编译器应该警告你这个问题。