我见过很多次std::string::operator[]
不做任何边界检查。偶What is the difference between string::at and string::operator[]? ,在 2013 年问,答案说 operator[]
不做任何边界检查。
我的问题是,如果我查看 [string.access] 中的标准(在本例中为 draft N3797),我们有
const_reference operator[](size_type pos) const; reference operator[](size_type pos);
- Requires:
pos <= size()
.- Returns:
*(begin() + pos)
ifpos < size()
. Otherwise, returns a reference to an object of typecharT
with valuecharT()
, where modifying the object leads to undefined behavior.- Throws: Nothing.
- Complexity: constant time.
这让我相信 operator[]
必须进行某种边界检查以确定它是否需要返回字符串的元素或默认 charT
.这个假设正确吗?operator[]
现在需要做边界检查吗?
最佳答案
措辞有些困惑,但如果你仔细研究它,你会发现它实际上非常精确。
上面写着:
- 前提条件是
[]
的参数要么是 = n 要么是 <n。 - 假设前提条件满足:
- 如果是 <n,那么你会得到你想要的字符。
- “否则”(即如果它是 n)然后你会得到
charT()
(即空字符)。
但是当你打破前提条件时没有定义规则,可以通过实际存储 charT()
在位置 n.
因此实现不需要执行任何边界检查……而普通的则不需要。
关于c++ - 在 C++11 及更高版本中,std::string::operator[] 是否进行边界检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38506473/