修改std :: string :: op []的结果是否合法? [英] Is it legal to modify the result of std::string::op[]?

查看:197
本文介绍了修改std :: string :: op []的结果是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从C ++ 11考虑以下内容:


[C ++ 11:21.4.5] : basic_string 元素存取                          [string.access]

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

1   需要: pos <= size()



/ sup>    返回: *(begin()+ pos) if pos< size(),否则引用 T ,值为 charT();参考值不得修改。



3  



4  

b

  • pos == size()大小写中的引用值不得修改,或

  • 任何情况下, op [] 返回的引用值不得修改,即使非 const overload。



第二种情况看起来完全可笑,但我认为这是最强烈的我们可以修改我们从 std :: string :: op [] 获得的内容。

解决方案

这个报价意味着你不能修改回报率 operator [](size()),即使值已明确定义。也就是说,即使通过非const重载,你也不能修改字符串中的NUL终结符。



这基本上是你的第一个选项:ie pos> = size(),但由于 pos <= size()的要求, c $ c> pos == size()。



语句的实际英语描述可能含糊不清(至少对我)但附录C,特别是C.2.11处理字符串库中语义的变化,没有提到这种改变 - 这将打破用户代码。在C ++ 03中,引用的值不应被修改。位不存在,没有歧义。在C.2.11中缺乏提及不是规范性的,但可以用作一个提示,当他们写标准时,没有意图改变这种特定的行为。


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?

解决方案

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.

这篇关于修改std :: string :: op []的结果是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆