c++ - 在 C++11 中,string::c_str() 指向的数组中的字符可以改变吗?

标签 c++ string c++11

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/

相关文章:

java - 如何在Java中逐行传递args?

python - Str 替换方法就地发生

c++ - 当仅提供一些模板参数时,C++编译器如何推断模板参数

c++ - 如何检查特定文件夹中是否存在任何文件?

c++ - 如何在 C/C++ 中运行阿克曼函数而不出错?

c++ - C++ 中的 STL : no match for 'operator*'

C++ 类相互引用(=> 错误 + 字段 '...' 的类型不完整)

c - 如何通过终端将段落读取为 C 中的单个字符串?

c++11 评估顺序(未定义行为)

带有元组的 C++ 可变参数模板