本文介绍了在C ++ 11和更高版本中,std :: string :: operator []做边界检​​查吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我已经看到很多次, std :: string :: operator [] 不做任何边界检查。即使是在C ++中,string :: at和string :: operator []?,在2013年问的答案说, operator [] 不做任何边界检查。 我的问题是,如果我看看标准(在这种情况下这让我相信 operator [] 必须做一些边界检查以确定是否需要返回字符串的元素或默认 charT 。这个假设是否正确, operator [] 现在需要做边界检查吗?解决方案 这说明: 前提条件是 [] 的参数是= n 或 。 假设前提条件满足: 那么你会得到你要求的字符。 否则(即如果是 charT()(即空字符)。 但是没有定义违反前提条件的规则,并且可以通过实际存储来隐式满足对 n 的检查(但没有明确强制要求) $ 不需要执行任何边界检查…而常见的则不会。 I have seen many times that std::string::operator[] does not do any bounds checking. Even In C++, what is the difference between string::at and string::operator[]?, asked in 2013, the answers say that operator[] does not do any bounds checking.My issue with this is if I look at the standard (in this case draft N3797) in [string.access] we have This leads me to believe that operator[] has to do some sort of bounds checking to determine if it needs to return a element of the string or a default charT. Is this assumption correct and operator[] is now required to do bounds checking? 解决方案 The wording is slightly confusing, but if you study it in detail you'll find that it's actually very precise.It says this:The precondition is that the argument to [] is either = n or it's < n.Assuming that precondition is satisfied:If it's < n then you get the character you asked for."Otherwise" (i.e. if it's n) then you get charT() (i.e. the null character).But no rule is defined for when you break the precondition, and the check for = n can be satisfied implicitly (but isn't explicitly mandated to be) by actually storing a charT() at position n.So implementations don't need to perform any bounds checking… and the common ones won't. 这篇关于在C ++ 11和更高版本中,std :: string :: operator []做边界检​​查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-03 06:14