Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

c++11

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.

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

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?

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;
}
like image 880
user2662157 Avatar asked Aug 07 '13 20:08

user2662157


People also ask

What is c_str () used for?

The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.

What does string c_str return?

The c_str method of std::string returns a raw pointer to the memory buffer owned by the std::string .

Why does c_str return Const?

The pointer returned by c_str is declared to point to a const char to prevent modifying the internal string buffer via that pointer. The string buffer is indeed dynamically allocated, and the pointer returned by c_str is only valid while the string itself does not change.

Is string c_str null terminated?

c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.


1 Answers

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

That requirement is still present as of draft n3337 (The working draft most similar to the published C++11 standard is N3337)

like image 58
Borgleader Avatar answered Oct 14 '22 08:10

Borgleader