简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM