In C++11 and beyond does std::string::operator[] do bounds checking?

前端 未结 5 918
南笙
南笙 2020-12-16 10:02

I have seen many times that std::string::operator[] does not do any bounds checking. Even What is the difference between string::at and string::operator[]?, as

5条回答
  •  情深已故
    2020-12-16 10:40

    First, there is a requires clause. If you violate the requires clause, your program behaves in an undefined manner. That is pos <= size().

    So the language only defines what happens in that case.

    The next paragraph states that for pos < size(), it returns a reference to an element in the string. And for pos == size(), it returns a reference to a default constructed charT with value charT().

    While this may look like bounds checking, in practice what actually happens is that the std::basic_string allocates a buffer one larger than asked and populates the last entry with a charT(). Then [] simply does pointer arithemetic.

    I have tried to come up with a way to avoid that implementation. While the standard does not mandate it, I could not convince myself an alternative exists. There was something annoying with .data() that made it difficult to avoid the single buffer.

提交回复
热议问题