Does "&s[0]" Always Point to Contiguous Characters in a std::string?
In maintenance code, some hasty reading may lead to concerns about using "&s[0]" to access characters in a std::string. This stems from the knowledge that, under C 98/03, std::string's allocation is not guaranteed to be contiguous, unlike in std::vector. However, C 11 has addressed this uncertainty.
Contrary to the standard, practical experience suggests that most implementations of std::string do allocate contiguous storage. Nevertheless, C 11 has definitively resolved this matter, mandating that std::string's allocation be contiguous. This ensures that "&s[0]" always points to a valid reference of the string's first character, even in situations where the string is empty.
While "&s[0]" remains a reliable method of accessing string characters, other methods like "str.begin()" and "&*str.begin()" are not guaranteed to work consistently under all standard configurations. Therefore, using "&s[0]" is the recommended approach for direct access to std::string's characters.
The above is the detailed content of Does `&s[0]` Always Point to Contiguous Characters in a C 11 `std::string`?. For more information, please follow other related articles on the PHP Chinese website!