For a C ++ string, s is s [s.size ()] legal and is always '\ 0'?

If s[s.size()]=='\0' , then it is convenient to consider it as a controller for some algorithm. I did a test and it is always '\0' , but some books say that it is illegal to access s[s.size()] .

+5
source share
1 answer

Yes, this will give a reference to a null character, as specified in the C ++ 11 standard:

Requires: pos <= size() .

Returns: *(begin() + pos) if pos < size() , otherwise a reference to an object of type T with value charT() ; reference value should not be changed.

where charT() is a value-based character that will have a null value. T is supposedly a typo for charT . The C ++ 14 project (and presumably the final standard) says the same thing as a typo fixed.

If you have a book that says otherwise, burn it or sell it to your enemies.

+9
source

Source: https://habr.com/ru/post/1214781/


All Articles