In C++11, can the characters in the array pointed to by string::c_str() be altered?

c++, c++11, string

Solution

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

That requirement is still present as of draft n3337 (The working draft most similar to the published C++11 standard is N3337)

Problem

`std::string::c_str()` returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. In C++98 it was required that "a program shall not alter any of the characters in this sequence". This was encouraged by returning a const char* . IN C++11, the "pointer returned points to the internal array currently used by the string object to store the characters that conform its value", and I believe the requirement not to modify its contents has been dropped. Is this true? Is this code OK in C++11? ``` #include<iostream> #include<string> #include<vector> using namespace std; std::vector<char> buf; void some_func(char* s) { s[0] = 'X'; //function modifies s[0] cout<<s<<endl; } int main() { string myStr = "hello"; buf.assign(myStr.begin(),myStr.end()); buf.push_back('\0'); char* d = buf.data(); //C++11 //char* d = (&buf[0]); //Above line for C++98 some_func(d); //OK in C++98 some_func(const_cast<char*>(myStr.c_str())); //OK in C++11 ? //some_func(myStr.c_str()); //Does not compile in C++98 or C++11 cout << myStr << endl; //myStr has been modified return 0; } ```

Original source

Related problems