std::string::c_str()
返回一个指向数组的指针,该数组包含一个以 null 结尾的字符序列(即 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;
}
最佳答案
3 Requires: The program shall not alter any of the values stored in the character array.
从草案 n3337 (The working draft most similar to the published C++11 standard is N3337) 开始,该要求仍然存在
关于c++ - 在 C++11 中,string::c_str() 指向的数组中的字符可以改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18113646/