Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::array operator[] vs get<>

Tags:

c++

c++11

According to cppreference.com:

get<> is enforced at compile time as opposed to at() or operator[].

Now I understand that at() does bounds checking, but I'd like to know the key difference between get and [] -- the page for operator[] says nothing about runtime enforcement of index, so maybe the quote above is not quite accurate.

They both take a size_type and return an element reference, so what is this "enforced at compile time" mean for get?

like image 489
Jerome Baldridge Avatar asked Jun 08 '26 16:06

Jerome Baldridge


2 Answers

You have basically three options when it comes to accessing elements in an std::array<T,n> container:

  • std::get<index>(arr) is checked at compile time. If the index is not constexpr or is outside the bounds [0,n) then you get a compile-time error. You should use it when you know that you want the first element, for example.
  • arr.at(index) is checked at runtime. If the index is outside the array bounds a std::out_of_range exception is thrown. This is similar to the behaviour of Java/.NET.
  • arr[index] is not checked at all. Maybe your compiler does it in debug builds, or maybe not. If the index is outside the bounds you get undefined behaviour, which means that literally all bets are off, so you should only use it when you are completely sure that your index is inside the bounds. The canonical case for this is traversing the array (index from 0 to size-1), but for that you would use a range-based for today.
like image 192
Javier Martín Avatar answered Jun 11 '26 06:06

Javier Martín


It means that if you have an std::array of size N, and you try to call get<i> on it, the program will only compile if i is in-bounds (0 <= i < N). Whereas, with operator[], the result of out-of-bounds access is undefined behaviour; the compiler may not be able to catch it for you.

like image 45
Brian Bi Avatar answered Jun 11 '26 05:06

Brian Bi