mercredi 20 février 2019

Using lambdas with auto declaration vs in-place?

I'm trying to learn modern C++ and I'm using Boost.Asio for networking. I wrote a TCP connection class, which uses Asio's asynchronous operations. This is currently my method for reading data from a socket:

template<class T>
inline auto connection<T>::read(size_t length) -> void
{
         auto handler = [&](const boost::system::error_code& error, size_t bytes_transferred) {
                if (error == boost::asio::error::eof or error == boost::asio::error::connection_reset) {
                        close();
                } else {
                        on_read(bytes_transferred);
                }
        };
        socket.async_read_some(boost::asio::buffer(read_buffer, length), handler);
}

Here I declared the read handler separately with auto, because I think it looks more readable than an in-place lambda, i.e.

template<class T>
inline auto connection<T>::read(size_t length) -> void
{
        socket.async_read_some(boost::asio::buffer(read_buffer, length), [&](const boost::system::error_code& error, size_t bytes_transferred) {
                if (error == boost::asio::error::eof or error == boost::asio::error::connection_reset) {
                        close();
                } else {
                        on_read(bytes_transferred);
                }
        });
}

However I ran into a segmentation fault with the first version, and I believe this is because the handler lambda is lost when the method goes out of scope. Then I tried to move the handler with std::move

socket.async_read_some(boost::asio::buffer(read_buffer, length), std::move(handler));

which seems to fix the segfault.

Now my question is: Are there any performance or other issues with using the first version (with std::move) vs in-place? Which one do you think is better practice?

Aucun commentaire:

Enregistrer un commentaire