2

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.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    Do you mean the underlying `string` structure and its dynamic buffer would be contiguous? How would that work if the string needed to grow beyond its initial allocation? – Jonathan Potter Jun 22 '15 at 10:47
  • @JonathanPotter The `string` could exist in a linked list for example? This would mean that calls to `string::data` and `string::c_str` would have to allocate temporary space. I just want to know what's required by the standard. – Jonathan Mee Jun 22 '15 at 10:58
  • 1
    perhaps you were looking for [Is it reasonable to use std::basic_string as a contiguous buffer when targeting C++03?](http://stackoverflow.com/q/2256160/1708801) – Shafik Yaghmour Jun 22 '15 at 11:22
  • @ShafikYaghmour That's a great link! I would have said, that was where I read his but I hadn't up-voted the anything on the page... so maybe not? – Jonathan Mee Jun 22 '15 at 11:25

1 Answers1

4

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.

Andrew
  • 5,212
  • 1
  • 22
  • 40
  • Exactly what I'm looking for, thank you, I'll accept shortly. It seems like this requirement *wasn't* in-place prior to C++11, but maybe I'm losing my mind. – Jonathan Mee Jun 22 '15 at 11:10
  • @JonathanMee Correct. The wording of the C++03 standard does not specify this constraint, and the wording of the sections on `c_str()` and `data()` imply that implementations may need to copy data around to make a contiguous block for those purposes (the requirement that the program doesn't modify it, or re-use the pointer after modifying operations on the string, for instance). Having said that, I don't know of any implementation that *doesn't* store strings contiguously... – Andrew Jun 22 '15 at 11:23