1

I am successfully establishing connection, sending and receiving messages using the following code. What I want to do is somehow to return that already established connection. I assume that I need to return the socket. Before writing this topic I read a few related topics - in some of them it was mentioned that returning a socket is not a good idea. Usage of shared is suggested here. Passing around boost::asio::ip::tcp::socket Unfortunately I am not familiar with this type of pointers and their usage. Could you help me with fixing that problem.

 try {
    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(server, port);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    my_socket = new tcp::socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    boost::asio::connect(*my_socket, endpoint_iterator);


    } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}
Community
  • 1
  • 1
Jason Per
  • 139
  • 2
  • 12
  • 2
    if you have c++11 or higher, ignore all that nonsense about shared pointers and return the socket. As of c++11 asio io objects support move construction and move assignment. An asio socket is extremely lighweight - the structure contains two pointers, nothing more. – Richard Hodges Dec 12 '16 at 23:23

1 Answers1

0

if you have c++11 or higher, ignore all that nonsense about shared pointers and return the socket. As of c++11 asio io objects support move construction and move assignment. An asio socket is extremely lighweight - the structure contains two pointers, nothing more. – Richard Hodges

Armali
  • 18,255
  • 14
  • 57
  • 171