I have seen many times that std::string::operator[] does not do any bounds checking. Even What is the difference between string::at and string::operator[]?, asked in 2013, the answers say that operator[] does not do any bounds checking.
My issue with this is if I look at the standard (in this case draft N3797) in [string.access] we have
const_reference operator[](size_type pos) const; reference operator[](size_type pos);
- Requires:
pos <= size().- Returns:
*(begin() + pos)ifpos < size(). Otherwise, returns a reference to an object of typecharTwith valuecharT(), where modifying the object leads to undefined behavior.- Throws: Nothing.
- Complexity: constant time.
This leads me to believe that operator[] has to do some sort of bounds checking to determine if it needs to return a element of the string or a default charT. Is this assumption correct and operator[] is now required to do bounds checking?
std::basic_string::operator[]not do bounds checking, it cannot and must not do bounds checking to be compliant. The standard specifically says this function throws nothing. - David Hammenpos >= size()and returncharT()if it wants to? - NathanOliverexit()doesn't throw and appears standards conforming. - Mooing Duckpos <= size()means ifpos > size()the behavior is undefined. So it can still legally throw something. - johnchen902