Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • 2
    Only c_str() guarantees a terminator at the end of the string. data() may point to an unterminated copy of the string, which is dangerous for most APIs that are expecting a const char *. Commented Oct 19, 2012 at 16:22
  • 3
    @AdrianMcCarthy: Depends on the version of C++ you are using. In C++11 data() is nul-terminated as well (and guaranteed to be valid even on empty strings). So in C++11 the only difference between c_str() and data() really is the const-ness. Commented Oct 19, 2012 at 18:26
  • @Matthieu M.: You're right--I was looking at the previous version of the spec. Still, there are a lot of people using old libraries, so the distinction might be important. Also c_str() is a little more suggestive of the intent. Commented Oct 19, 2012 at 19:43
  • @AdrianMcCarthy: Yes, the distinction really is important. Both the non nul-terminated and the "undefined" if empty aspects! The C++03 spec left more margin for implementation, but in doing so it made it opened more undefined holes. Commented Oct 20, 2012 at 13:35