Paavo Helde
11/24/2008 10:11:00 PM
Juha Nieminen <nospam@thanks.invalid> kirjutas:
> Paavo Helde wrote:
>> More verbosely, I should probably note that the contiguity of the
>> string buffer obtained by &x[0] is not guaranteed by the standard,
>> but all known C++ implementations are following that, and the
>> requirement will be present in the next standard AFAIK.
>
> Do practical implementations of std::string always use a contiguous
> array (in the same as std::vector) because it makes it much more
> efficient for the std::string::c_str() to do its job (basically it
> just needs to append a '\0' and then return a pointer to the array)?
It also has to do with thread-safety. Although the current standard does
not mention multithreading, a quality implementation attempts to provide
some useful support for it. For the string objects, them being value
types, this means that they should not mutate physically in const member
functions. This means that the c_str() and data() member functions cannot
alter the actual string buffer, for example making a contiguous array
from the non-contiguous pieces the string was held in so far. At most
they could construct a new buffer and return pointer to it, but in this
case the question of memory ownership comes up; this could be resolved by
having some pool of owned buffers inside the string object, but I guess
this already becomes an overkill for such a basic class. It seems the
simplest and most robust version is to have a single contiguous buffer,
always zero-terminated for the case somebody might call c_str(), and
modified only by mutating member functions.
Note, these are just my thoughts about the subject, I have not
implemented standard library, so I may be deeply mistaken.
Paavo