string c_str() vs. data()

The documentation is correct. Use c_str() if you want a null terminated string.

If the implementers happend to implement data() in terms of c_str() you don’t have to worry, still use data() if you don’t need the string to be null terminated, in some implementation it may turn out to perform better than c_str().

strings don’t necessarily have to be composed of character data, they could be composed with elements of any type. In those cases data() is more meaningful. c_str() in my opinion is only really useful when the elements of your string are character based.

Extra: In C++11 onwards, both functions are required to be the same. i.e. data is now required to be null-terminated. According to cppreference: “The returned array is null-terminated, that is, data() and c_str() perform the same function.”

Leave a Comment