* Noah Roberts:
I have a situation in which a function expects a char const* and uses
the supplied address directly. It's a GUI element in a particular
platform but the question is generic.
I could give it the c_str() return of the string and expect that the
string isn't going to change, if it does send the c_str() again.
I could give it &str[0].
I could use a vector and do the same as the second string method.
I could also just use a raw array but I see no real advantage in that.
From a portability or design standpoint is there any /real/ difference
in the first three choices?
The c_str() result is only guaranteed to be valid as long as the
std::string instance exists and no mutating operations are performed.
This may matter if the GUI element doesn't copy the string.
&str[0] is not guaranteed to be zero-terminated. Pedantically, under
the current standard it's not guranteed to be a pointer to a contiguous
buffer, either, but for all practical purposes you can ignore that.
A vector has the advantage that folks not familiar with the standard's
evolution and existing compiler practice, may not think you're doing a
dangerous thing (they'll think, rightly, that the buffer is contiguous).
It has the disadvantage that if the string comes from elsewhere in the
form of a std::string, you'll have to copy the data.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?