How to asynchronously read to std::string using Boost::asio?

前端 未结 4 1669
野性不改
野性不改 2020-12-08 11:55

I\'m learning Boost::asio and all that async stuff. How can I asynchronously read to variable user_ of type std::string? Boost::asio::buffer(user_)

4条回答
  •  一向
    一向 (楼主)
    2020-12-08 12:10

    You can use a std:string with async\_read() like this:

    async_read(socket_, boost::asio::buffer(&user_[0], user_.size()),
               boost::bind(&Connection::handle_user_read, this,
               placeholders::error, placeholders::bytes_transferred));
    

    However, you'd better make sure that the std::string is big enough to accept the packet that you're expecting and padded with zeros before calling async\_read().

    And as for why you should NEVER bind a member function callback to a this pointer if the object can be deleted, a more complete description and a more robust method can be found here: Boost async_* functions and shared_ptr's.

提交回复
热议问题