1

I am trying to put the acceptor, socket and endpoint as members into my class but ran into crashes. Must the socket be a shared_ptr like in this Question or why does it not work?

When I'm trying to setup a acceptor on a server like this:

tcp::endpoint ep(boost::asio::ip::address::from_string(localIpAddress), portNumber);
tcp::acceptor a(io_service);
tcp::socket s(io_service);
a.open(ep.protocol());
a.bind(ep);
a.listen(MAX_CONNECTIONS);
a.async_accept(s, boost::bind(&WifiConnector::onAccept, this, boost::asio::placeholders::error));

it runs without crashing during execution, but when I try to use a socket/acceptor/endpoint that are member of my WifiConnector class it crashes.

m_acceptor.open(localEndpoint.protocol()); // it crashes in this line already
m_acceptor.bind(localEndpoint);
m_acceptor.listen(MAX_CONNECTIONS);
m_acceptor.async_accept(socket, boost::bind(&WifiConnector::onAccept, this, boost::asio::placeholders::error));

declaration in WifiConnector.hpp:

private:
    tcp::socket m_socket;
    tcp::acceptor m_acceptor;
    tcp::endpoint m_localEndpoint;

initialization at class constructor:

WifiConnector::WifiConnector() :
    io_service(),
    m_socket(io_service),
    m_acceptor(io_service)
{
    m_localIpAddress    = "192.168.137.1";
    m_portNumber        = 30000;
    m_localEndpoint = tcp::endpoint(boost::asio::ip::address::from_string(m_localIpAddress), m_portNumber);
}

when it crashes, I get the following exeption:

boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >
kenba
  • 4,303
  • 1
  • 23
  • 40
MrJonas
  • 197
  • 11
  • Given that the problem arises when you refactor the code into a class, I think you really need to provide a [mcve]. Failing that, can you at least show the declaration of `WifiConnector::io_service`? – G.M. Nov 24 '17 at 10:06

1 Answers1

-1
private:
    tcp::socket m_socket;
    tcp::acceptor m_acceptor;
    tcp::endpoint m_localEndpoint;

This will not work. You are constructing using the default constructors, which is not what you want. For one thing you want to construct using the io_service used by everything else.

Make the attributes pointers, and construct them using new when you have the io_service.

MrJonas
  • 197
  • 11
ravenspoint
  • 19,093
  • 6
  • 57
  • 103
  • The default constructor is not used (it is not possible b/c there is none for socket etc,) but the right constructors are called (including the io_service) when the WifiConnector constructor is called see "initialization at class constructor" – MrJonas Nov 23 '17 at 17:24