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...
views:
630answers:
2I figured it would be something simple I'd overlooked - thanks!
fbrereto
2009-10-07 21:47:25
In reality though, they probably point to the same thing (not that you should rely on it).
Zifre
2009-10-07 21:48:04
@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
2009-10-07 22:07:52
+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
2009-10-07 21:46:58