* James Kanze:
[...]
Yes, modulo terminology that's correct, and I wrote that in my
first response. In case you misunderstood that, here's a
reworded version: c_str() is not the opposite of a conversion
of your data to std::string, because c_str(), as you mention,
appends a null-byte, and there's no such in your original
data, and because your original data contains a zero byte
which can't appear within a proper zero-termianted string
(only at the end of it). The closest you get to the "the other
way" is &s[0].
What's wrong with s.data() (using it with s.size(), of course)?
(And of course, &s[0] isn't yet formally guaranteed, although it
will be, and does work with all known implementations.)
But easier, since you don't have to stretch your fingers for any
unusual characters. With a French or German keyboard (which
don't have a [ or a ]), you even need to use some implementation
dependent means of entering it
. And data() expresses the
intent much better.
may be just a wrapper for c_str(), and IIRC is lacking in
const department.
In which way? In the current standard, it is a const function
which returns a const char* (and of course, in the current
standard, any use of &s[0] to access anything but the first
character is undefined behavior). In the next version of the
standard (which will guarantee contiguity), there will be both a
const and a non-const version (and the other container which
guarantees contiguous-ness, std::vector, will also have a const
and a non-const data() function).
But mainly, it's just non-idiomatic.
In what way? I regularly use std::string::data() when that's
what I need (as opposed to a null terminated string---of
course, most of the time, when I need something like that, I'll
be useing an std::vector said:
I guess, since it has no clear advantage for anything, people
just don't use it.
Except that people do. I've seen s.data() a lot more than
&s[0]. It wasn't clear until very recently that &s[0] was in
fact reliable, since people were always talking about some
(mythical) implementation where the actual data wasn't
contiguous.