I've been coding in c and wanted to try out boost asio to create a TCP asynchronous server.
I read the documentation that boost provides and I used boost 1.75 to try and code this server.
However, I don't seem to understand how to use the io_context from the documentation.
When I am compiling the code for the Day 3: Asynchronous TCP daytime server (this link which is in boost 1.78 but doesn't seem to differ a lot from 1.75) I constantly get the error that io_context cannot be copied due to their inheritance from execution_context, which inherits from noncopyable
.
So I don't understand how to write and compile the documentation code since it tries to make a copy of an io_context in it.
Thanks in advance for any replies.
Edit : I've been compiling the code on C 17 and used conan to manage boost, the problem I am having comes from the constructor where I try to copy an io_context to an attribute of my class :
class Server {
public:
Server(boost::asio::io_context& io_context) : _io_context(io_context), _acceptor(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 13))
{
startAccept();
}
~Server();
private:
void startAccept();
void handleAccept(ConnectionHandler::pointer new_connection, const boost::system::error_code &error);
boost::asio::io_context _io_context;
boost::asio::ip::tcp::acceptor _acceptor;
};
And here are the compilation error I was getting with the example :
error: use of deleted function
‘boost::asio::io_context::io_context(const boost::asio::io_context&)’17 | Server(boost::asio::io_context& io_context) :
_io_context(io_context), _acceptor(io_context,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 13))
/home/romsnouk/.conan/data/boost/1.75.0/_/_/package/634391908be52704fdd5c332658475fe91ab3b1d/include/boost/asio/io_context.hpp:639:3: note: declared here
639 | io_context(const io_context&) BOOST_ASIO_DELETED;
CodePudding user response:
The problem? When you try to initialize the _io_context
member you copy the un-copyable io_context
object.
The _io_context
member needs to be a reference:
boost::asio::io_context& _io_context;
// ^
// Note ampersand, to make it a reference
This is what's done in the full example.
Of course make sure that the life-time of the original io_context
object is at least as long as the Server
object you create.