Vector::at vs. vector::operator[] -- 不同的行为

Vector::at vs. vector::operator[] -- different behaviour

本文关键字:vs at vector operator Vector      更新时间:2023-10-16
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
class sample
{
public:
    sample()
    {
        cout << "consructor called" << endl;
    }
    void test()
    {
        cout << "Test function" << endl;
    }
};
int main()
{
    vector<sample> v;
    sample s;
    v.push_back(s);
    try
    {
        v.at(1).test();  // throws out of range exception.
        v[1000].test();  // prints test function
    }
    catch (const out_of_range& oor)
    {
        std::cerr << "Out of Range error: " << oor.what() << 'n';
    }
    return 0;
}

为什么v[1000].test();在屏幕上打印测试功能。我在矢量中只添加了一个对象。我同意我可以访问v[1000]因为它是顺序的。但是为什么它会给出完全正确的结果呢?提前谢谢。

vector::at(( 显式抛出越界异常,而 vector::operator 没有这样做。通过设计。

某些 std 实现支持在调试模式下检查运算符 [] 边界。

由于您的test()方法不访问任何实例变量并且this因此即使指向不存在的位置this也可以毫无问题地执行它。