FrozenHeart FrozenHeart - 1 year ago 49
C++ Question

Is it permitted to modify the internal std::string buffer returned by operator[] in C++11

Is there any rules in the standard that violates modifications of internal

buffer returned by
like this:

void foo(char* buf)
buf[1] = 's';

std::string str = "str";

I found the following quote in the C++11 draft about

Requires: The program shall not alter any of the values stored in the character array.

But I don't see any about

Answer Source


operator[] returns a reference to the character. So if the string is NOT const, you can modify it safely.

For C++ 11, the characters are stored contiguously, so you can take &str[0] as the beginning of the underlying array whose size is str.size(). And you can modify any element between [ &str[0], &str[0] + str.size() ), if the string is NOT const. e.g. you can pass &str[0] and str.size() to void func(char *arr, size_t arr_size): func(&str[0], str.size())

data() and c_str() members

For C++11 and C++14, both data() and c_str() returns const CharT*, so you CANNOT modify element with the returned pointer. However, from C++17, data() will return CharT*, if string is NOT const. And data() will be an alias to &str[0].