views:

630

answers:

2

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

+11  A: 

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

Jerry Coffin
I figured it would be something simple I'd overlooked - thanks!
fbrereto
In reality though, they probably point to the same thing (not that you should rely on it).
Zifre
@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
+3  A: 

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