Why would I ever want to call std::string::data()
over std::string::c_str()
? Surely there is some method to the standard's madness here...
Asked
Active
Viewed 7,255 times
16
-
5Would just like to point out that in the next version of C++ [C++11 or C++0x or whatever you want to call it], the two functions are synonymous by definition. – Dennis Zickefoose Jul 06 '11 at 22:33
3 Answers
19
c_str() guarantees NUL termination. data() does not.

Jerry Coffin
- 476,176
- 80
- 629
- 1,111
-
-
1In reality though, they probably point to the same thing (not that you should rely on it). – Zifre Oct 07 '09 at 21:48
-
6@Zifre: they may point to the same address, but after a mutating operation (str += "..." ), the implementation could leave the internal data buffer without the null termination, and only add the '\0' when the c_str() method is called. – David Rodríguez - dribeas Oct 07 '09 at 22:07
-
2Note that this is no longer true from C++11 on (data() is the same as c_str()) – Adriweb Jul 18 '17 at 07:34
5
c_str() return a pointer to the data with a NUL byte appended so you can use the return value as a "C string".
data() returns a pointer to the data without any modifications.
Use c_str() if the code you are using assumes a string is NUL terminated (such as any function written to handle C strings).

R Samuel Klatchko
- 74,869
- 16
- 134
- 187
1
Now in MS STL 10.0 there doesn't seem to be any difference, as I see this in the header:
...\Microsoft Visual Studio 10.0\VC\include\xstring
const _Elem *c_str() const
{ // return pointer to null-terminated nonmutable array
return (_Myptr());
}
const _Elem *data() const
{ // return pointer to nonmutable array
return (c_str());
}
So they return the same thing.

C.J.
- 15,637
- 9
- 61
- 77
-
-
This is behavior that is allowed by the current standard, and required by the next one. I suspect most libraries have been doing this for a while now, in preparation of the change over. – Dennis Zickefoose Jul 07 '11 at 05:16