Is it possible to use an std::string for read()?

c++, sockets, stdstring

Solution

Well, you'll need to create a `char*` somehow, since that's what the function requires. (BTW: you are talking about the Posix function `read`, aren't you, and not `std::istream::read`?) The problem isn't the `char*`, it's what the `char*` points to (which I suspect is what you actually meant).

The simplest and usual solution here would be to use a local array:

char buffer[43];
int len = read(fd, buffer, 42);
if ( len < 0 ) {
    //  read error...
} else if ( len == 0 ) {
    //  eof...
} else {
    std::string data(buffer, len);
}

If you want to capture directly into an `std::string`, however, this is possible (although not necessarily a good idea):

std::string data;
data.resize( 42 );
int len = read( fd, &data[0], data.size() );
//  error handling as above...
data.resize( len );  //  If no error...

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 more years ago. The original specifications for `std::string` were designed expressedly to allow non-contiguous implementations, along the lines of the then popular `rope` class. In practice, no implementor found this to 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.)

Problem

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

Original source