Opened 5 years ago

Last modified 4 years ago

#13477 new Bugs

Initializing boost::asio socket after constructor failed

Reported by: nguyen.tnhoang@… Owned by: chris_kohlhoff
Milestone: To Be Determined Component: asio
Version: Boost 1.66.0 Severity: Showstopper
Keywords: c++ asio boost shared_ptr boost::ref Cc:

Description

I create a class to broadcast UDP messages as in the attached socket.cpp file. It works fine. Then, I wish to initialize the socket after the class constructor is initialized (to allow user input). So, I change from using socket to a socket pointer as in the socketPtr.cpp.

It is a solution suggested by this post (https://stackoverflow.com/questions/31371214/initializing-boostasio-sockets-after-constructor).

The replacements are as follows, where io_service is wrapped as boost::ref(io_service):

boost::asio::ip::udp::socket socket; boost::shared_ptr<udp::socket> socketPtr;

boost::asio::ip::udp::socket socket(io_service, endpoint.protocol()); socket.set_option(boost::asio::ip::udp::socket::reuse_address(true)); socketPtr = boost::make_shared<udp::socket>(boost::ref(io_service), endpoint.protocol()); socketPtr->set_option(boost::asio::ip::udp::socket::reuse_address(true));

socket.async_send_to(boost::asio::buffer(message), endpoint, [this](boost::system::error_code ec, std::size_t /*length*/) socketPtr->async_send_to(boost::asio::buffer(message), endpoint, [this](boost::system::error_code ec, std::size_t /*length*/)

Just one thing with the modification: it doesn't work. I keep poring over the code, and could not find the reason why it shouldn't work. Could someone please help?

Attachments (2)

socket.cpp (5.3 KB ) - added by nguyen.tnhoang@… 5 years ago.
socketPtr.cpp (5.4 KB ) - added by nguyen.tnhoang@… 5 years ago.

Download all attachments as: .zip

Change History (3)

by nguyen.tnhoang@…, 5 years ago

Attachment: socket.cpp added

by nguyen.tnhoang@…, 5 years ago

Attachment: socketPtr.cpp added

comment:1 by Krishna, 4 years ago

I have the same issue. I want to initialize udp socket in my class constructor


server_udp_socket = boost::asio::ip::udp::socket(*my_io_service,

server_endpoint);


I am seeing the same issue. Is there a solution to this issue, except using initializers ?

Note: See TracTickets for help on using tickets.