不,它肯定不安全,没有任何asio async_* 函数被记录为“即发即弃”。
basic_datagram_socket::async_send缓冲区的 boost asio 引用指出:“虽然缓冲区对象可能会根据需要被复制,但调用者保留底层内存块的所有权,它必须保证它们在调用处理程序之前保持有效。” </p>
如果您需要“一劳永逸”的方法,那么您需要一个类来管理您的连接并为您缓冲数据包。这是一个使用双端队列缓冲数据包的示例:
class Connection : public boost::enable_shared_from_this<Connection>
{
boost::asio::ip::udp::socket socket_;
std::deque<std::vector<char> > tx_queue_;
/// transmit the packet at the head of the queue
void transmit()
{
socket_.async_send(
boost::asio::buffer(&tx_queue_.front()[0], tx_queue_.front().size()),
boost::bind(&Connection::write_callback,
boost::weak_ptr<Connection>(shared_from_this()),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/// The function called whenever a write event is received.
void write_handler(boost::system::error_code const& error,
size_t /* bytes_transferred */)
{
tx_queue_.pop_front();
if (error)
; // handle the error, it may be a disconnect.
else
if (!tx_queue_.empty())
transmit();
}
/// Static callback function.
/// It ensures that the object still exists and the event is valid
/// before calling the write handler.
static void write_callback(boost::weak_ptr<Connection> ptr,
boost::system::error_code const& error,
size_t bytes_transferred)
{
boost::shared_ptr<Connection> pointer(ptr.lock());
if (pointer && (boost::asio::error::operation_aborted != error))
pointer->write_handler(error, bytes_transferred);
}
/// Private constructor to enusure the class is created as a shared_ptr.
explicit Connection(boost::asio::io_service& io_service) :
socket_(io_service),
tx_queue_()
{}
public:
/// Factory method to create an instance of this class.
static boost::shared_ptr<Connection> create(boost::asio::io_service& io_service)
{ return boost::shared_ptr<Connection>(new Connection(io_service)); }
/// Destructor, closes the socket to cancel the write callback
/// (by calling it with error = boost::asio::error::operation_aborted)
/// and free the weak_ptr held by the call to bind in the transmit function.
~Connection()
{ socket_.close(); }
/// add the packet to the end of the queue and send it ASAP.
#if defined(BOOST_ASIO_HAS_MOVE)
void send(std::vector<char>&& packet)
#else
void send(const std::vector<char>& packet)
#endif
{
bool queue_empty(tx_queue_.empty());
tx_queue_.push_back(packet);
if (queue_empty)
transmit();
}
};