在C ++ 11和更高版本中,std :: string :: operator []做边界检​​查吗? [英] In C++11 and beyond does std::string::operator[] do bounds checking?

查看:224
本文介绍了在C ++ 11和更高版本中,std :: string :: operator []做边界检​​查吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多次, std :: string :: operator [] 不做任何边界检查。即使是在C ++中,string :: at和string :: operator []?,在2013年问的答案说, operator [] 不做任何边界检查。



我的问题是,如果我看看标准(在这种情况下


 

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




  1. 需要: pos <= size()

  2. 返回: *(begin if pos< size()。否则,返回对 charT 的值为 charT()的对象的引用,其中修改对象导致未定义行为。

  3. 投掷没有任何东西。

  4. >


这让我相信 operator [] 必须做一些边界检查以确定是否需要返回字符串的元素或默认 charT 。这个假设是否正确, operator [] 现在需要做边界检查吗?



这说明:




  • 前提条件是 [] 的参数是= n 或<


  • 假设前提条件满足:


    • 那么你会得到你要求的字符。

    • 否则(即如果是< $ c> charT()(即空字符)。




但是没有定义违反前提条件的规则,并且可以通过实际存储来隐式满足对<= em> 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

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

  1. Requires: pos <= size().
  2. Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.
  3. Throws: Nothing.
  4. Complexity: constant time.

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 []做边界检​​查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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