Can "&s[0]" Reference Consecutive Characters in a std::string?
It has been noticed that code like this:
std::string s; s.resize( strLength ); memcpy( &s[0], str, strLength );
would be safe if s was a std::vector, but the question is whether it is a safe use of std::string.
In C 98/03, a std::string's allocation is not guaranteed to be contiguous. However, C 11 enforces this contiguity. In practice, most implementations use contiguous storage.
The use of &s[0] is guaranteed by the C 11 standard to work, even for zero-length strings. This is because the operator[] is defined as:
Returns *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified
Additionally, data() is defined as:
Returns: A pointer p such that p + i == &s[i] for each i in [0,size()].
Therefore, "&s[0]" points to consecutive characters in a std::string and is a safe usage.
The above is the detailed content of Is `&s[0]` a Safe and Contiguous Pointer to Characters in a C std::string?. For more information, please follow other related articles on the PHP Chinese website!