Home >Backend Development >C++ >Is C 11's `std::string` Guaranteed to Be Null-Terminated?

Is C 11's `std::string` Guaranteed to Be Null-Terminated?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 14:37:13516browse

Is C  11's `std::string` Guaranteed to Be Null-Terminated?

std::string Null-Termination in C 11

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn