Opened 9 years ago

Closed 8 years ago

#9023 closed Feature Requests (invalid)

asio::io_service::wrap() docs need an example

Reported by: vinnie.falco@… Owned by: chris_kohlhoff
Milestone: To Be Determined Component: asio
Version: Boost 1.54.0 Severity: Cosmetic
Keywords: Cc:

Description

The documentation for io_service::wrap reads:

Return Value A function object that, when invoked, passes the wrapped handler to the io_service object's dispatch function. Given a function object with the signature:

To say that this is cryptic would be an understatement. An example should be provided. One of the most common cases for calling io_service::wrap is when you want to post your own completion parameters for a given handler. For example, in your composed operation when an error occurs, you simply want to call the handler with the error_code.

Here's an example from a piece of my own code. Note how the ReadHandler is posted to the io_service with a default-constructed error_code and bytes_transferred from the result of asio::buffer_copy:

    template <typename MutableBufferSequence, typename ReadHandler>
    BEAST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (error_code, std::size_t))
    async_read_some (MutableBufferSequence const& buffers,
        BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
    {
        using namespace boost;
        if (m_buffer.size () > 0)
        {
            std::size_t const bytes_transferred = asio::buffer_copy (
                buffers, m_buffer.data ());
            return get_io_service ().wrap (
                BOOST_ASIO_MOVE_CAST(ReadHandler)(handler)) (
                    error_code (), bytes_transferred);
        }

        return m_next_layer.async_read_some (buffers,
            BOOST_ASIO_MOVE_CAST(ReadHandler)(handler));
    }

The addition of an example of a call to io_service::wrap would help illuminate this useful case.

Change History (1)

comment:1 by chris_kohlhoff, 8 years ago

Resolution: invalid
Status: newclosed

This is not intended as a valid use case for wrap(). The wrap() function is documented to use dispatch(), but the requirements on asynchronous operations state that an operation must behave as if implemented using post().

Regarding your specific example, a better approach is to still call the m_next_layer.async_read_some() function inside your if-block, but with a zero-length buffer. The AsyncReadStream type requirements say that this shall complete immediately, so you can use it as a replacement for post(), but with the added benefit of reducing the number of template instantiations.

Note: See TracTickets for help on using tickets.