C++11 Allocation Requirement on Strings

岁酱吖の 提交于 2019-12-02 05:54:09

问题


I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it.

I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just asking as to the standard's requirements.


回答1:


Section 21.4.1.5 of the 2011 standard states:

The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().

The two parts of the identity expression are

  1. Take the begin() iterator, advance by n, then dereference and take the address of the resulting element.
  2. Take the begin() iterator, dereference and take the address of the resulting element. Add n to this pointer.

Since both are required to be identical, this enforces contiguous storage; that is, the iterator cannot move over any non-contiguous storage without violating this requirement.



来源:https://stackoverflow.com/questions/30977974/c11-allocation-requirement-on-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!