In C++11, can the characters in the array pointed to by string::c_str() be altered?

后端 未结 4 720
情深已故
情深已故 2021-01-01 21:57

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 t

4条回答
  •  囚心锁ツ
    2021-01-01 22:38

    I have verified that this is in the published C++11 standard

    Thank you

    what's wrong with &myStr.front()?

    string myStr = "hello";
    char* p1 = const_cast(myStr.c_str());
    char* p2 = &myStr.front();
    p1[0] = 'Y';
    p2[1] = 'Z';
    

    It seems that pointers p1 and p2 are exactly the same. Since "The program shall not alter any of the values stored in the character array", it would seem that the last two lines above are both illegal, and possibly dangerous.

    At this point, the way I would answer my own question is that it is safest to copy the original std::string into a vector and then pass a pointer to the new array to any function that might possibly change the characters.

    I was hoping that that this step might no longer be necessary in C++11, for the reasons I gave in my original post.

提交回复
热议问题