Home > Backend Development > C++ > Is std::string in C 11 Guaranteed to be Null-Terminated?

Is std::string in C 11 Guaranteed to be Null-Terminated?

Linda Hamilton
Release: 2024-12-07 20:27:13
Original
832 people have browsed it

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()].
Copy after login

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!

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