在C ++ 11中,可以改变由string :: c_str()指向的数组中的字符? [英] In C++11, can the characters in the array pointed to by string::c_str() be altered?

查看:136
本文介绍了在C ++ 11中,可以改变由string :: c_str()指向的数组中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: string :: c_str()返回一个指向数组的指针,该数组包含一个以null结束的字符序列

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.

在C ++ 98中,要求程序不得更改此序列中的任何字符。这是通过返回一个const char *。鼓励的。

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* .

在C ++ 11中,指针返回指向字符串对象当前使用的内部数组来存储字符符合其价值,我认为不修改其内容的要求已经放弃。这是真的?

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?

这是C ++ 11中的代码吗?

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


推荐答案


3要求:程序不得更改存储在字符数组中的任何值。

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

n3337(与公布的C ++ 11标准最相似的工作草案是N3337

这篇关于在C ++ 11中,可以改变由string :: c_str()指向的数组中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆