A std::string’s allocation is not guaranteed to be contiguous under the C++98/03 standard, but C++11 forces it to be. In practice, neither I nor Herb Sutter know of an implementation that does not use contiguous storage.
Notice that the
&s thing is always guaranteed to work by the C++11 standard, even in the 0-length string case. It would not be guaranteed if you did
&*str.begin(), but for
&s the standard defines
*(begin() + pos)if
pos < size(), otherwise a reference to an object of type
charT(); the referenced value shall not be modified
data() is defined as:
Returns: A pointer
p + i == &operator(i)for each
(notice the square brackets at both ends of the range)
Notice: pre-standardization C++0x did not guarantee
&s to work with zero-length strings (actually, it was explicitly undefined behavior), and an older revision of this answer explained this; this has been fixed in later standard drafts, so the answer has been updated accordingly.