is there guaranteed behaviour attempting access character @ -1
in std::string?
eg if do:
for (int = 0; < str.size(); i++) { if (str[i-1] == 'a' && str[i+1] == 'c') { //etc } }
then on first iteration str[-1]
, standard happen? know says in c++11 str[str.size()] return null character, sites cppreference , cplusplus don't other out of bounds accesses.
(if run code above, nothing bad happens, want make sure standard)
is there guaranteed behaviour access character @ -1 in std::string?
formally, depends. in practice, undefined behaviour, there no guarantees.
the parameter of operator[]
unsigned, -1
maximum value type can hold (std::numeric_limits<std::string::size_type>::max()
). since maximum value std::string::size()
can hold, defined only in (extremely improbable) case string has largest size allowed, in case reference null terminator returned.
from c++11 standard, , n3936 draft of c++14 standard,
21.4.5 basic_string element access [string.access]
const_reference operator[](size_type pos) const; reference operator[](size_type pos);
- requires:
pos <= size()
.- returns:
*(begin() + pos)
ifpos < size()
. otherwise, returns reference object of typechart
valuechart()
, modifying object leads undefined behavior. ....
Comments
Post a Comment