Does "&s[0]" Reference Contiguous Characters in a std::string?
In C , using "&s[0]" to access the first character of a std::string has been a common practice, but concerns arise regarding its safety in this context. Understanding the underlying storage scheme of std::string is crucial to address this issue.
The C 98/03 standard did not enforce contiguous storage for std::string allocations, making it possible for implementations to use fragmented memory. However, with the advent of C 11, contiguous storage became a mandatory requirement for std::string.
In practice, it's highly unlikely to encounter an implementation that deviates from the contiguous storage approach. As Herb Sutter acknowledges, no known implementation violates this convention.
Therefore, using "&s[0]" to reference the first character of a std::string is safe in both C 98/03 and C 11. The C 11 standard explicitly guarantees this behavior, even for zero-length strings. This is evident from the definition of operator[]:
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, the data() function is defined as:
Returns: A pointer p such that p + i == &operator[](i) for each i in [0, size()].
These definitions confirm that the reference obtained through "&s[0]" points to a valid character within the string, which is contiguous by default in modern C implementations.
The above is the detailed content of Is `&s[0]` a Safe Way to Access the First Character of a std::string in C ?. For more information, please follow other related articles on the PHP Chinese website!