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;
}