Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use brackets [] or .at() for array access?

Tags:

c++

arrays

Since the at() function in C++ arrays and vectors provides out-of-bounds checking and there is not a significant performance difference in using operator[] instead, should one ever use brackets for array access?

Perhaps only in performance-critical code?

like image 711
J-Win Avatar asked Dec 02 '22 12:12

J-Win


2 Answers

You should use [] when you are certain that no "out-of bounds" access will happen.

You should use at() when "out of bounds" access may happen and you are prepared to either deal with that (by catching the exception and doing something sensible) or your program crashing is ok (which it would anyway had you used [], just in an undefined manner).

like image 114
Jesper Juhl Avatar answered Dec 05 '22 06:12

Jesper Juhl


You shouldn't use any of them. std::vector provides iteration capabilities that rarely make necessary to explicitly access an item by index.

To answer your question, following the don't pay for what you don't use, if you know that you are not going to go out of bounds there is no need to use at().

Otherwise you should always check a pointer for not being nullptr every time you are going to dereference it, but in practice you don't do it if you are sure that it's a valid pointer.

like image 26
Jack Avatar answered Dec 05 '22 06:12

Jack