Boost Thread: Use of deleted function Error

2019-09-07 02:57发布

问题:

I am trying to use a multi-threading in boost to handle multiple requests and upon the reception of a specific message I will create a new thread to handle it as below:

main.cpp

/** * Destination Machine Request Handler. * * @param msg Received message. * @param ec Error code. */ void handover_request_handler(odtone::mih::message &msg, const boost::system::error_code &ec) { if (ec) { log_(0, FUNCTION, " error: ", ec.message()); return; } // Do some stuff }

void event_handler(odtone::mih::message &msg, const boost::system::error_code &ec) { if (ec) { log_(0, FUNCTION, " error: ", ec.message()); return; }

switch (msg.mid()) { // Destination Cloud Server received HO Commit Message case odtone::mih::indication::n2n_ho_commit: { boost::thread thrd(boost::bind(&handover_request_handler, msg, ec)); thrd.join(); } break; }

}

When I try to compile it using b2 tool, I get the following errors:

gcc.compile.c++ ../../bin.v2/app/lte_mih_usr/gcc-4.6/debug/link-static/runtime-link-static/main.o main.cpp: In function ‘void event_handler(odtone::mih::message&, const boost::system::error_code&)’: main.cpp:189:69: error: use of deleted function ‘odtone::mih::message::message(const odtone::mih::message&)’ In file included from ../../inc/odtone/mih/request.hpp:24:0, from main.cpp:11:

So how to solve this problem?

Thanks a lot.

回答1:

The thread constructor copies its arguments, and the message type is not copyable. To pass a reference to the target function you need to use boost::ref(msg)

Also note that using bind with thread is unnecessary:

boost::thread thrd(&handover_request_handler, boost::ref(msg), boost::ref(ec));

The thread constructor implements the same semantics as bind, so using bind just adds unnecessary additional copying.