Home >Backend Development >C++ >Is C 11's `std::string` Guaranteed to Be Null-Terminated?
In C 11, the behavior of std::string regarding null-termination remains an important topic. As discussed in previous discussions, Herb Sutter proposed tightening the requirements in C 0x to enforce null-termination and potentially prohibit copy-on-write implementations for concurrency reasons.
The final draft of C 11 did adopt these proposals. According to [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 crucial requirement implies that given a string s, the pointer returned by s.c_str() must be equal to the address of the initial character in the string (&s[0]). Consequently, it is now safe to utilize &str[0] to access the underlying character array of std::string. This behavior ensures consistent and reliable null-termination, making it suitable for compatibility with C-style null-terminated strings.
The above is the detailed content of Is C 11's `std::string` Guaranteed to Be Null-Terminated?. For more information, please follow other related articles on the PHP Chinese website!