std::string::c_str() 返回一个指向数组的指针,该数组包含一个以空字符结尾的字符序列(即一个C字符串),表示字符串对象的当前值.
在C++ 98中,要求"程序不得改变此序列中的任何字符".通过返回const char*来鼓励这一点.
在C++ 11中,"指针返回指向字符串对象当前使用的内部数组,以存储符合其值的字符",我相信不删除修改其内容的要求.这是真的?
这段代码在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;
}
Run Code Online (Sandbox Code Playgroud)