C ++ 11字符串的分配要求 [英] C++11 Allocation Requirement on Strings
问题描述
我听说C ++ 11需要 string
s在连续内存中分配。我甚至认为我看到一个堆栈溢出问题,但我似乎找不到它。
I had heard that C++11 was going to require string
s 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.
我知道在实践中,gcc和Visual Studio做分配<
I know that in practice both gcc and Visual Studio do allocate string
s contiguously, I'm just asking as to the standard's requirements.
推荐答案
p> 2011年标准的第21.4.1.5节规定:
Section 21.4.1.5 of the 2011 standard states:
basic_string
对象应该连续存储
。也就是说,对于任何basic_string
对象s
,标识
& (s.begin()+ n)==& * s.begin()+ n
将适用于
n
使得0 <= n < s.size()
。
The char-like objects in a
basic_string
object shall be stored contiguously. That is, for anybasic_string
objects
, the identity&*(s.begin() + n) == &*s.begin() + n
shall hold for all values ofn
such that0 <= n < s.size()
.
身份表达式的两部分是
- 以
begin()
迭代器前进n
,然后取消引用并获取结果元素的地址。 - 使用
begin()
迭代器,的所得元素。将n
添加到此指针。
- Take the
begin()
iterator, advance byn
, then dereference and take the address of the resulting element. - Take the
begin()
iterator, dereference and take the address of the resulting element. Addn
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.
这篇关于C ++ 11字符串的分配要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!