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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With