从 asio::ip::tcp::socket 直接写入 std::string

Write from asio::ip::tcp::socket directly to std::string

我试图在不复制的情况下从 asio 套接字读取到 std::string。 此实现似乎有效,但我不确定它是否可靠。

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;
}

是的,行得通。不过直接用会快很多:

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

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

这样你就可以避免 C-style 重新解释演员表的所有令人讨厌的事情。 (顺便也抛弃了const)