Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will std::string always be null-terminated in C++11?

In a 2008 post on his site, Herb Sutter states the following:

There is an active proposal to tighten this up further in C++0x and require null-termination and possibly ban copy-on-write implementations, for concurrency-related reasons. Here’s the paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2534.html . I think that one or both of the proposals in this paper is likely to be adopted, but we’ll see at the next meeting or two.

I know that C++11 now guarantees that the std::string contents get stored contiguously, but did they adopt the above in the final draft?

Will it now be safe to use something like &str[0]?

like image 933
links77 Avatar asked May 20 '11 20:05

links77


People also ask

Are std :: strings always null-terminated?

Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .

Does string end with null in C++?

In C the strings are basically array of characters. In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0').

Can std::string be null?

Thus, NULL isn't a valid value for a std::string. They *can't* really be NULL. The relevant overloads for std::string are to compare a std::string to a std::string, a char* to a std::string, or a std::string to a char*.

How are C++ strings terminated?

It is known as the null character, or NUL, and standard C strings are null-terminated. This terminator signals code that processes strings - standard libraries but also your own code - where the end of a string is.


1 Answers

Yes. Per the C++0x FDIS 21.4.7.1/1, std::basic_string::c_str() must return

a pointer p such that p + i == &operator[](i) for each i in [0,size()].

This means that given a string s, the pointer returned by s.c_str() must be the same as the address of the initial character in the string (&s[0]).

like image 66
James McNellis Avatar answered Oct 20 '22 05:10

James McNellis