0
点赞
收藏
分享

微信扫一扫

C++:关于std::vector两个方法operator[]和at使用上的区别(转)

拾光的Shelly 2021-09-25 阅读 46
随笔

operator[]和at的主要区别在于operator[]不做边界检查,而at会做边界检查。

由于operator[]不做边界检查, 那怕越界了也会返回一个引用,当然这个引用是错误的引用,如何不小心调用了这个引用对象的方法,会直接导致应用退出。

而由于at会做边界检查,如果越界,会抛出异常,应用可以try catch这个异常,应用还能继续运行。

结论:使用at时应使用try catch包裹住;而使用operator[]时一定要先检查一下是否越界。

void doTest01() {
    try {
        std::vector<std::string> vec;
 
        string& i = vec[2];
 
        cout << i.size() << endl;
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
    catch (...) {
        cerr << "error" << endl;
    }
};
 
void doTest02() {
    try {
        std::vector<std::string> vec;
 
        string& i = vec.at(2);
 
        cout << i.size() << endl;
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
    catch (...) {
        cerr << "error" << endl;
    }
 
};

doTest01()中,try catch不起作用,应用会直接退出。

doTest02()中,会catch异常,应用不会退出。

转载:https://blog.csdn.net/netyeaxi/article/details/82765703

举报

相关推荐

0 条评论