0
#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;
}

Why v[1000].test(); printing test function on the screen. I have added only one object in the vector. I agree I can access v[1000] becuase its sequential. But why it is giving the exactly correct result? Thanks in advance.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • 2
    Accessing `v[1000].test()` on a `std::vector` of size 1 is a [nasal demon](http://en.wikipedia.org/wiki/Undefined_behavior). – Pixelchemist Feb 19 '15 at 06:37

1 Answers1

1

vector::at() explicitly throws out of bound exception while vector::operator is not doing that. By design.

Some std implementations support operator[] bounds checking in debug mode.

As your test() method is not accessing any instance variables and this then it can be executed without problem even this points to non-existent location.

c-smile
  • 26,734
  • 7
  • 59
  • 86