Is it valid to create an iterator to end(str)+1
for std::string
?
And if it isn't, why isn't it?
This question is restricted to C++11 and later, because while pre-C++11 the data was already stored in a continuous block in any but rare POC toy-implementations, the data didn't have to be stored that way.
And I think that might make all the difference.
The significant difference between std::string
and any other standard container I speculate on is that it always contains one element more than its size
, the zero-terminator, to fulfill the requirements of .c_str()
.
21.4.7.1 basic_string accessors [string.accessors]
const charT* c_str() const noexcept; const charT* data() const noexcept;
1 Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
in[0,size()]
.
2 Complexity: Constant time.
3 Requires: The program shall not alter any of the values stored in the character array.
Still, even though it should imho guarantee that said expression is valid, for consistency and interoperability with zero-terminated strings if nothing else, the only paragraph I found casts doubt on that:
21.4.1 basic_string general requirements [string.require]
4 The char-like objects in a
basic_string
object shall be stored contiguously. That is, for anybasic_string
objects
, the identity&*(s.begin() + n) == &*s.begin() + n
shall hold for all values ofn
such that0 <= n < s.size()
.
(All quotes are from C++14 final draft (n3936).)
Related: Legal to overwrite std::string's null terminator?
See Question&Answers more detail:os