vendredi 2 septembre 2016

Behaviour of accessing a character at index -1 for std::string?

Is there any guaranteed behaviour for access the character at -1 in a std::string?

Eg if I do:

for (int i = 0; i < str.size(); i++) {
  if (str[i-1] == 'a' && str[i+1] == 'c') {
    //etc
  }
}

Then on the first iteration it will do str[-1], what does the standard say will happen? I know it says in C++11 that str[str.size()] will return the null character, but sites like cppreference and cplusplus don't say anything about other out of bounds accesses.

(if I run the code above, then nothing bad happens, but I want to make sure that this is standard)

Aucun commentaire:

Enregistrer un commentaire