16

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

pnuts
  • 58,317
  • 11
  • 87
  • 139
fbrereto
  • 35,429
  • 19
  • 126
  • 178
  • 5
    Would 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 Answers3

19

c_str() guarantees NUL termination. data() does not.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I figured it would be something simple I'd overlooked - thanks! – fbrereto Oct 07 '09 at 21:47
  • 1
    In 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
  • 2
    Note 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
  • It also looks like it's exactly the same in VC 9.0 too. – C.J. Jul 06 '11 at 22:31
  • 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