Tip of the Week #224: Avoid vector.at()
▻https://abseil.io/tips/224
Originally posted as TotW #224 on August 24, 2023
By Titus Winters
Updated 2024-01-24
Quicklink: abseil.io/tips/224
There is no good use of vector::at() in google3, and fairly few good uses in other C++ environments. The same reasoning applies to at() on other random-access sequences like RepeatedPtrField in protobuf, as well as to value() on wrapper types like optional and absl::StatusOr.
What Does at() Do?
The specification of at(size_type pos) is as follows:
Returns a reference to the element at specified location pos, with bounds checking. If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
This means we could view the contract of this method as two distinct behaviors:
Check whether pos >= size(), and if so then throw a (...)