3

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?

2
  • 2
    The key difference is get<> is enforced at compile time as opposed to operator[]. Commented Jun 21, 2016 at 20:49
  • 1
    @juanchopanza that is exactly what i've written in my question. Can you explain further? Commented Jun 21, 2016 at 20:50

2 Answers 2

9

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.
Sign up to request clarification or add additional context in comments.

Comments

7

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.

3 Comments

So if i is not known at compile time, you cannot use get?
@JXB yes, since it is a template parameter
@JXB also note that std::vector has no get<> because its size may be unknown at compile time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.