Search code examples
c++boostboost-asioshared-ptrboost-bind

Boost::Bind noncopyable error with shared_ptr <tcp::socket>


I am trying the following:

boost::shared_ptr< tcp::socket > socket(new tcp::socket( *io_service));

boost::bind(&function, *socket); // compiler error: noncopyable error
function(*socket); // this works fine

void
function(tcp::socket & socket)
{
   //do work
}

Why do I get an error there using boost::bind?

I later tried the following:

boost::shared_ptr< tcp::socket > socket(new tcp::socket( *io_service));
boost::bind(&function, socket); //this works fine now
void function(boost::shared_ptr< tcp::socket > socket)
{
   asio::read_until(&socket, buffer, "end"); // compiler error: says i am passing an invalid argument
}

Why doesn't this work now?

I know I am lacking basic knowledge of C/C++ programming.

If anyone could include a link that helps with issues like this, it would be great.


Solution

  • tcp::socket is non-copyable, you need to pass it as a reference:

    boost::bind(&function, boost::ref(*socket)); 
    

    You should probably stick to your second version as you will not have to worry about life-time of the socket object.

    boost::bind(&function, socket); 
    void function(boost::shared_ptr< tcp::socket > socket)
    {
       asio::read_until(*socket, buffer, "end");
    }