Home >Backend Development >C++ >Is std::string in C 11 Guaranteed to be Null-Terminated?
Null Termination in C 11's std::string
In C , strings are typically represented using the std::string class. Prior to C 11, there was ambiguity regarding whether std::string objects were always null-terminated.
C 11 Guarantee of Contigious Storage
In C 11, the std::string class gained a guarantee that its contents would be stored contiguously. This addressed one of the concerns raised by Herb Sutter in his 2008 article.
Adoption of Null Termination Proposal
As for the requirement for null termination and the ban on copy-on-write implementations, the proposals mentioned in Sutter's article were not fully adopted in the final draft of C 11.
Safety of Using &str[0]
However, as per [string.accessors] p1, std::basic_string::c_str():
Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].
This means that the pointer returned by s.c_str(), where s is a string, is equivalent to the address of the initial character in the string (&s[0]).
Therefore, in C 11, it is safe to use &str[0] to access the first character of a std::string object, assuming it is not modified by external factors.
The above is the detailed content of Is std::string in C 11 Guaranteed to be Null-Terminated?. For more information, please follow other related articles on the PHP Chinese website!