Passing a socket pointer using tcp :: acceptor :: async_accept

I recently started using Boost.Asio in a project and would like to know if anyone knows a clean decision to transfer ownership of the newly created socket to tcp :: acceptor :: async_accept, which in turn will transfer this ownership to the function accept handler.

This is not an incoherent desire, mind you, since the handler must be called exactly once.

I noticed that I can not set std :: bind () as std :: unique_ptr <> as a parameter, since std :: bind () requires its parameters to be CopyConstructible, and this is true. Not only that, but the Boost AcceptHandler concept is also required by CopyConstructible.

So my options are:

  • Go to the deprecated std :: auto_ptr <> way to move objects using the copy constructor, which potentially causes unclear errors in new releases of Boost.Asio.
  • Use std :: shared_ptr <> and not be able to disable sharing with the pointer if it is no longer needed, that is, when it reaches the actual function of the handler (this is how the task is executed using examples at http://www.boost.org /doc/libs/1_43_0/doc/html/boost_asio/examples.html as far as I read).

or

  • You have a better idea for me.

I am pretty much lost here. Can anyone enlighten me?

+3
source share
1 answer

, ++ 0x, . rvalue_reference_wrapper rvalue_ref(). std:: bind, , (reference_wrapper - ). , .

:

#include <iostream>
#include <functional>
#include <memory>

template< class T >
struct rvalue_reference_wrapper
{
    rvalue_reference_wrapper( T&& t )
        : t_(std::move(t))
    {}

    operator T&&() const volatile
    {
        return std::move(t_);
    }

private:
    T&& t_; 
};

template< class T >
rvalue_reference_wrapper<T> rvalue_ref( T&& t )
{
    return rvalue_reference_wrapper<T>(std::move(t));
}

void go( std::unique_ptr<int> i )
{
    std::cout << *i << std::endl;
}

int main()
{
    std::unique_ptr<int> i(new int(1));

    auto b = std::bind( go, rvalue_ref(std::move(i)) );
    //auto b = std::bind( go, std::ref(std::move(i)) ); // Wont work

    b();
}

, rvalue_reference_wrapper , , std:: reference_wrapper.

, , , rvalue_reference_wrapper, rvalue, unique_ptr, , ( ), asio.

+1

Source: https://habr.com/ru/post/1751055/


All Articles