FrozenHeart
FrozenHeart

Reputation: 20746

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 std::string buffer returned by operator[] like this:

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

std::string str = "str";
modify_buffer(&str[0]);

I found the following quote in the C++11 draft about data and c_str functions:

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

But I don't see any about operator[].

Upvotes: 7

Views: 3752

Answers (1)

for_stack
for_stack

Reputation: 22946

operator[]

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].

Upvotes: 11

Related Questions