我在类中重载了shift运算符以提供输入。我在该方法中执行同步asio::write()
,然后立即执行异步asio::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
如果我将引用传递给socket:
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;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
答案 0 :(得分: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);
});