Shibli
Shibli

Reputation: 6149

To use "at" or [] to access member of std::vector safely

I had an array

arr[10]

It tried to access

arr[12]

and program did not do anything until I realized when I switched to vectors. Somewhere I read that if I use [] then program would not give any runtime error again so that I should use std::vector's at. But in my program I just used [] and it helped me to spot the problem. It seems [] is enough. Am I right? Also, is there any bound check for arrays for safety?

Upvotes: 3

Views: 1349

Answers (2)

bames53
bames53

Reputation: 88235

Some implementations of the C++ library have a debug mode that will throw an exception even when you use the [] syntax, but this is not specified by the standard. So that may be what you experienced. If you want to be sure you should use at().

C++ doesn't have bounds checking for primitive arrays, however if your compiler supports the newest version of C++ then you can use std::array instead of primitive arrays, and this container has an at() method just like std::vector.

I'd recommend using std::array even if you don't want this feature because primitive arrays have some other problems (e.g. they decay to pointers at the drop of a hat). std::array behaves much more consistently (e.g. you can pass them by value to functions or return them and they'll work correctly whereas writing the obvious syntax to pass an array by value will fail and will instead just pass a pointer).

Do yourself a favor and never use primitive arrays.

Upvotes: 9

WeaselFox
WeaselFox

Reputation: 7400

the at() function signals if the requested position is out of range by throwing an exception, and is therefore safer.

Upvotes: 3

Related Questions