Using operator[] , you essentially tell the compiler: “I know what I'm doing. Trust me.” If you access some element outside the array, this is your mistake. You have broken this trust; you did not know what you were doing.
An alternative is to use the at() method. Here you ask the compiler to perform a health check on access. If they are out of bounds, you get an exception.
This health check can be expensive, especially if it runs in some deeply nested loop. There is no reason for these sanity checks if you know that indexes will always be within. It is nice to have an interface that does not perform these health checks.
The reason for creating operator[] is one that does not perform validation, because this is exactly how [] works for raw arrays and pointers. In C / C ++, there is no health check to check access to raw arrays / pointers. The burden rests with you to verify this, if necessary.
source share