What's the difference between std::string::c_str and std::string::data? [duplicate]
Asked Answered
W

3

17

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

Worcestershire answered 7/10, 2009 at 21:43 Comment(1)
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.Nev
P
19

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

Prod answered 7/10, 2009 at 21:46 Comment(4)
I figured it would be something simple I'd overlooked - thanks!Worcestershire
In reality though, they probably point to the same thing (not that you should rely on it).Familiar
@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.Levirate
Note that this is no longer true from C++11 on (data() is the same as c_str())Shorter
J
6

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

Jaxartes answered 7/10, 2009 at 21:46 Comment(0)
T
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.

Twyla answered 6/7, 2011 at 22:7 Comment(2)
It also looks like it's exactly the same in VC 9.0 too.Twyla
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.Nev

© 2022 - 2024 — McMap. All rights reserved.