2

I'm trying to read from an asio socket into a std::string without copying. This implementation seems to work but I'm not sure if it is reliable.

string read(int bytes)
{
    string str;
    str.resize(bytes);
    char* buffer = (char*) str.data();
    //socket is declared as class member
    asio::read(socket,asio::buffer(buffer,bytes));
    return str;
}
Freggar
  • 1,049
  • 1
  • 11
  • 24
  • 1
    Your question falls into the general category of "can I write directly to the `std::string` buffer?". [Looks like a duplicate](http://stackoverflow.com/questions/25169915/is-writing-to-str0-buffer-of-a-stdstring-well-defined-behaviour-in-c11) – PaulMcKenzie Jan 28 '17 at 06:12
  • What makes you unsure? – Mikel F Jan 28 '17 at 06:18
  • @PaulMcKenzie yeah that was pretty much the answer I was looking for but is `string.data()` and `&string[0]` the same? – Freggar Jan 28 '17 at 08:28
  • The documentation here http://en.cppreference.com/w/cpp/string/basic_string/data says: `data() + i == &operator[](i) for every i in [0, size()]`. Insert `i == 0` and you get yes :) – Matthias247 Jan 28 '17 at 12:28
  • @PaulMcKenzie In principle. In practice, though, Asio has specific provisions for it, which are relevant (contrast the answers to see what I mean) – sehe Jan 29 '17 at 02:16

1 Answers1

2

Yes that works. But it will be a lot more expeditious to use it directly:

std::string read(int bytes)
{
    std::string str;
    str.resize(bytes);

    asio::read(socket, asio::buffer(str));
    return str;
}

That way you avoid all the nasty ness of your C-style reinterpret cast. (Which incidentally also cast away const)

sehe
  • 374,641
  • 47
  • 450
  • 633