Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider the following from C++11:

[C++11: 21.4.5]: basic_string element access                           [string.access]

const_reference operator[](size_type pos) const;
reference       operator[](size_type pos);

1     Requires: pos <= size().

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

3     Throws: Nothing.

4     Complexity: constant time.

This means either:

  • The referenced value in the pos == size() case shall not be modified, or
  • In any case, the referenced value returned by op[] shall not be modified, even for the non-const overload.

The second scenario seems completely ridiculous, but I think it's what the wording most strongly implies.

Can we modify what we get from std::string::op[], or not? And is this not rather ambiguous wording?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

The quote means that you cannot modify the return of operator[]( size() ), even if the value is well defined. That is, you must not modify the NUL terminator in the string even through the non-const overload.

This is basically your first option: i.e. pos >= size(), but because of the requirement pos <= size() the only possible value for that condition is pos == size().

The actual English description of the clause can be ambiguous (at least to me), but Appendix C, and in particular C.2.11 deals with changes in semantics in the string library, and there is no mention to this change --that would break user code. In C++03 the "referenced value shall not be modified" bit is not present and there is no ambiguity. The lack of mention in C.2.11 is not normative, but can be used as a hint that when they wrote the standard there was no intention on changing this particular behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...