On 19.10.2019 12:16, Soviet_Mario wrote:
> On 18/10/2019 17:21, Paavo Helde wrote:
>> On 18.10.2019 12:50, Frederick Gotham wrote:
>>>
>>> I read this today:
>>> "Vector is guaranteed to store all elements in contiguous locations"
>>>
>>> Is this true?
>>
>> Yes, this has been true formally since 2003. For strings a similar
>> guarantee was introduced in C++11.
>
> but strings means the "descriptors", not the actual text data, right ? I
> mean, there is a further indirection before accessing the content,
> comparing to native types, or am I wrong ? If so, even if the array of
> pointers is monolythic, the true text data of each item should still be
> "sparse", or not ?
I was comparing std::string to std::vector<char>, not to
std::vector<std::string>. The contiguousness guarantee for a std::string
formalized in 2005 or 2011 just means that &s[0] + i == &s[i] inside a
single string.
Regarding std::vector<std::string>, the std::string objects in a
std::vector are still contiguous, i.e. you can fetch out a std::string*
pointer via data() and just use pointer arithmetic to access other
std::string objects in the contiguous buffer. But you are right, this
does not mean the character data of all those strings were contiguous or
even in order in memory, typically they would be all scattered around.
If the string implementation uses small string optimization and all
strings are small enough, then the character arrays would reside
directly inside the std::string objects, making them to be in order and
somewhat "contiguous" in memory, but not quite.
Regardless of implementation details it is physically impossible to have
the character data of more than one std::string contiguous in memory,
because the character array of each string has to be followed by a zero
byte (to satisfy the const c_str() member function requirements), but
this zero byte is not considered to be a part of the character data of
the string. So the character arrays of two different strings cannot be
contiguous, there must be at least one zero byte between them.