问题
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]?
回答1:
Yes. Per the C++0x FDIS 21.4.7.1/1, std::basic_string::c_str() must return
a pointer
psuch thatp + i == &operator[](i)for eachiin[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]).
来源:https://stackoverflow.com/questions/6077189/will-stdstring-always-be-null-terminated-in-c11