Home > Backend Development > C++ > Is std::string Contiguously Stored and Null-Terminated in C 11?

Is std::string Contiguously Stored and Null-Terminated in C 11?

Barbara Streisand
Release: 2024-12-30 00:42:10
Original
990 people have browsed it

Is std::string Contiguously Stored and Null-Terminated in C  11?

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template