簡體   English   中英

不拋出 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()返回一個無符號值。 所以在比較兩個數字之前-1被轉換成一個無符號值。 此轉換以最大的unsigned值加 1 為模完成,這意味着-1被轉換為最大可能的unsigned值。 然后將其與向量的大小進行比較,這種比較總是錯誤的。

由於這個原因,有符號/無符號比較是有問題的。 盡管定義明確,但如果帶符號值為負,則它們不會以數學上預期的方式工作。 你的編譯器應該警告你這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM