2016-10-17 53 views
0

我已經重載班級中的移位運算符來提供輸入。我在該方法中執行同步asio::write(),然後立即執行異步asio::async_read()。我的問題是,班次超載需要成爲我班的朋友。使用來自朋友方法的async_read

如果我提供這async_read:

void operator>>(const vector<unsigned char> input, Socket &socket) { 
     const size_t size = input.size(); 
     const size_t bytes = asio::write(socket.connection_socket, asio::buffer(input, size)); 
     if (bytes != size) { 
     const std::error_code ec; 
     throw std::system_error(ec, fmt::format("Tried to send {0} bytes but sent {1} instead.", size, bytes)); 
     } 
     asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           this, 
           std::placeholders::_1)); 
    } 

我得到的錯誤:

error: invalid use of 'this' outside of a non-static member function 

如果我通過參考座:

void operator>>(const vector<unsigned char> input, Socket &socket) { 
     const size_t size = input.size(); 
     const size_t bytes = asio::write(socket.connection_socket, asio::buffer(input, size)); 
     if (bytes != size) { 
     const std::error_code ec; 
     throw std::system_error(ec, fmt::format("Tried to send {0} bytes but sent {1} instead.", size, bytes)); 
     } 
     asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           socket, 
           std::placeholders::_1)); 
    } 

我得到的錯誤:

error: call to implicitly-deleted copy constructor of 'std::__1::__bind<void 
     (databaseclient::internal::Socket::*)(std::__1::error_code &, unsigned long), databaseclient::internal::Socket &, std::__1::placeholders::__ph<1> &>' 
    ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; 
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

回答

2

您綁定到套接字的副本,這是非法的。

這是更好的:

asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           std::ref(socket), 
           std::placeholders::_1)); 

這是更好(因爲綁定是不合時宜):

asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         [&socket](auto const& ec, auto transferred) 
         { 
         handle_async_read(socket, ec); 
         });