Because many errors in C++ have no defined effects but instead result in undefined behaviour. Passing an impossible index to std::string
's operator[]
is an example of such an error. Anything or nothing can happen.
This is because requiring compilers to create programs which perform all kinds of error checking at runtime would severely reduce the usability of C++ in usage scenarios where the overhead of error checking would be unacceptable. Generally, if you want runtime error checking like this in C++, then you have to ask for it (and pay for it).
A rather simplistic way would be to use the at
member function, which is required to throw exceptions for illegal string indices. But how would you "handle" an exception like this, other than with an ugly catch
in main
which logs an error and quits?
An illegal string index should be treated as a bug which has to be fixed, not "handled" at runtime. Fortunately, there are ways to tell compilers to add detection of a wrong operator[]
at runtime. Here's some more information:
Note that only size
is relevant to determine whether accessing an element is undefined behaviour or not. capacity
is not.