C ++ internal buffer address undefined

The following behavior is undefined in the C ++ 11 standard:

(tries to get the address of the internal buffer of the string)

std::string s;
... = &s[0];

      

like when s

empty?

I know what we have c_str(), data()

, but nonetheless.

Note

This comes from a debate with someone, this is not intended to promote hacky coding

+3


source to share


2 answers


In C ++ 11, the code is well defined, but may not do what you expect. Exact Effects: 21.4.5 / 2:

Returns: *(begin() + pos)

if pos < size()

, otherwise a reference to an object of type T

with a value charT()

; the reference value should not be changed.



So, if the string is not empty, it returns a reference to the beginning of the internal buffer. If empty, it returns a reference char

with a value 0

whose location is implementation information.

+7


source


I think this will give you an address somewhere on your stack. By optimizing small strings in most implementations.

http://www.cplusplus.com/reference/string/string/operator [[]] says:



If pos is equal to the length of the string, the function returns a reference to the null character that follows the last character in the string that should not be changed.

You may have problems with undefined behavior as soon as your index parameter is larger than the string size.

0


source







All Articles