8

这个问题没有与之相关的实际问题,更多的是出于好奇和想知道我是否过于字面意思;)。

所以我一直在努力尽可能多地理解 c++ 标准。今天在研究标准时,我注意到了这一点(ISO/IEC 14882:2003 21.3.4):

const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Returns: If pos < size(), returns data()[pos].
         Otherwise, if pos == size(), the const version returns charT().
         Otherwise, the behavior is undefined.

对我来说似乎很理智。但后来我心想,等一下,“?”的定义是data()什么?

const charT* data() const;

是的,它返回一个.const charT*

显然,非 const 版本operator[]不能实现为简单的return data()[pos]then ,因为那会char&从 type 的表达式初始化 type 的引用const char

我认为很明显,意图data()实现类似的东西return data_;operator[]实现为return data_[pos];或功能相似的东西,但这不是标准所说的:-P。

如果我没记错的话,实施者有一些回旋余地,只要满足给定的基本要求并具有相同的净效果,他们就可以按照自己的意愿实施。

所以问题是,我是不是太直白了,还是这种类型的东西会被认为是缺陷。

编辑:值得注意的是,c++0x 草案已将措辞更改为:

Returns: If pos < size(), returns *(begin() + pos).
         Otherwise, if pos == size(), the const version returns charT().
         Otherwise, the behavior is undefined.

所以也许我刚刚偶然发现了一些已经讨论过的东西。

4

2 回答 2

6

Yes, it was a defect and yes, this was the fix.

http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#259

于 2010-07-06T21:17:29.507 回答
1

I assume that they used data() in the definition instead of data_ becuase they wanted to define in strictly in terms of the public interface.

于 2010-07-06T19:29:16.923 回答