不抛出 std::out_of_range 异常

Byr*_*onB 3 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
        }

     
Run Code Online (Sandbox Code Playgroud)

如果我使用无效索引访问 for 循环中的向量元素,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
    }
Run Code Online (Sandbox Code Playgroud)

joh*_*ohn 15

因为循环不执行。-1 < vd.size()是假的。

size()返回一个无符号值。所以在比较之前将两个数字-1转换为无符号值。这种转换是以unsigned最大值加一为模完成的,这意味着-1转换为最大的可能unsigned值。然后将其与向量的大小进行比较,这种比较总是错误的。

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