jeudi 24 novembre 2016

Wrong value for captured value when calling boost resolve::async_resolve

I can't understand the behaviour of the code below. When defining the symbol BUG, the third print of the variable this is wrong.

I think there is something in the method resolver::async_resolve that break the code. I'd like to understand what :-)

Thanks

#include <boost/asio.hpp>
#include <iostream>

using namespace std;

template <typename F>
#ifdef BUG
void Connect( boost::asio::ip::tcp::resolver& resolver, F Connected )
#else
void Connect( boost::asio::ip::tcp::resolver& resolver, const F& Connected     )
#endif
{
    resolver.async_resolve(
        boost::asio::ip::tcp::resolver::query{ "localhost", "8088" },
        [&Connected]( const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator i )
        {
            Connected();
        }
    );
}

struct Test
{
    void Start()
    {
        cout << "this1 " << hex << this << dec << endl;
        auto handler = [this]()
        {
            cout << "this2 " << hex << this << dec << endl;
            boost::asio::ip::tcp::resolver resolver{ ios };
            Connect( resolver, [this]()
                {
                    cout << "this3 " << hex << this << dec << std::endl;
                }
            );
        };
        handler();
        ios.run();
    }

    boost::asio::io_service ios;
};

int main()
{
    Test t;
    t.Start();
}

Aucun commentaire:

Enregistrer un commentaire