Is it possible to use an std::string for read() ?
Example :
std::string data;
read(fd, data, 42);
Normaly, we have to use char* but is it possible to directly use a std::string ? (I prefer don’t create a char* for store the result)
Thank’s
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, you’ll need to create a
char*somehow, since that’s what thefunction requires. (BTW: you are talking about the Posix function
read, aren’t you, and notstd::istream::read?) The problem isn’tthe
char*, it’s what thechar*points to (which I suspect is whatyou actually meant).
The simplest and usual solution here would be to use a local array:
If you want to capture directly into an
std::string, however, this ispossible (although not necessarily a good idea):
This avoids the copy, but quite frankly… The copy is insignificant
compared to the time necessary for the actual read and for the
allocation of the memory in the string. This also has the (probably
negligible) disadvantage of the resulting string having an actual buffer
of 42 bytes (rounded up to whatever), rather than just the minimum
necessary for the characters actually read.
(And since people sometimes raise the issue, with regards to the
contiguity of the memory in
std:;string: this was an issue ten or moreyears ago. The original specifications for
std::stringwere designedexpressedly to allow non-contiguous implementations, along the lines of
the then popular
ropeclass. In practice, no implementor found thisto be useful, and people did start assuming contiguity. At which point,
the standards committee decided to align the standard with existing
practice, and require contiguity. So… no implementation has ever not
been contiguous, and no future implementation will forego contiguity,
given the requirements in C++11.)