Is std::string Contiguously Stored and Null-Terminated in C 11?
In a previous discussion, concerns were raised regarding the memory layout and null-termination of std::string in C 0x. Herb Sutter proposed requiring null-termination and banning copy-on-write implementations for concurrency reasons.
C 11 Guarantees Contiguous Storage
As mentioned in the question, C 11 ensures that std::string contents are stored contiguously. However, the question remains unanswered whether the proposals regarding null-termination were adopted in the final draft of C 11.
Null-Termination in C 11
Per the C 11 standard [string.accessors] p1, std::basic_string::c_str() states:
"Returns a pointer p such that p i == &operator[](i) for each i in [0,size()],"
meaning the pointer returned by s.c_str() is equivalent to the address of the initial character in the string (&s[0]). Therefore, std::string is guaranteed to be null-terminated in C 11.
Usage Implications
The null-termination guarantee means it is safe to use &str[0] to access the first character of a std::string in C 11, ensuring compatibility with legacy code that relies on this behavior.
The above is the detailed content of Is std::string Contiguously Stored and Null-Terminated in C 11?. For more information, please follow other related articles on the PHP Chinese website!