我有以下代码使用 Boost ASIO 来设置 TCP 客户端。这是我改编自 Boost doc's chat example的代码。
class AsioCommunicationService {
AsioCommunicationService::AsioCommunicationService(
boost::asio::io_service& io_service,
tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
socket_(io_service)
{
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect(endpoint,
boost::bind(&AsioCommunicationService::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
void AsioCommunicationService::handle_connect(const boost::system::error_code& error,
tcp::resolver::iterator endpoint_iterator)
{
if (!error)
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), LampMessage::header_length),
boost::bind(&AsioCommunicationService::handle_read_header, this,
boost::asio::placeholders::error));
}
}
}
class Connection
{
//init io_service, query, resolve, iterator here
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(host, service);
boost::asio::ip::tcp::resolver::iterator endpoint_iterator =
resolver.resolve(query);
m_session = std::shared_ptr<AsioCommunicationService>(
new AsioCommunicationService(io_service, iterator));
//start new thread for io_service.run --> GOT AN ERROR when include boost/thread.hpp
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
//this synchronous command would work, but it's blocking the program. I don't want that.
//io_service.run();
}
当然,我需要包含 boost/thread 才能在 Connection 类中对变量 t 进行声明。但是当我这样做时,我得到了这个错误
#include <boost/thread.hpp>
//ERROR: In function ‘boost::thread&& boost::move(boost::thread&&)’:
///usr/include/boost/thread/detail/thread.hpp:349:16: error: invalid initialization of reference of type ‘boost::thread&&’ from expression of type ‘boost::thread’
//In file included from /usr/include/boost/thread/detail/thread_heap_alloc.hpp:17:0,
// from /usr/include/boost/thread/detail/thread.hpp:13,
// from /usr/include/boost/thread/thread.hpp:22,
// from /usr/include/boost/thread.hpp:13,
// from /home/son/dev/logistics/src/frameworks/networkService/NetworkConnection.cpp:13:
///usr/include/boost/thread/pthread/thread_heap_alloc.hpp: In function ‘T* boost::detail::heap_new(A1&&) [with T = boost::detail::thread_data<void (*)()>, A1 = void (*&)()]’:
///usr/include/boost/thread/detail/thread.hpp:130:95: instantiated from here
///usr/include/boost/thread/pthread/thread_heap_alloc.hpp:24:47: error: cannot bind ‘void (*)()’ lvalue to ‘void (*&&)()’
///usr/include/boost/thread/detail/thread.hpp:43:13: error: initializing argument 1 of ‘boost::detail::thread_data<F>::thread_data(F&&) [with F = void (*)()]’
如果我删除对 boost/thread.hpp 的包含,它会编译并工作,并通过对 io_service.run(); 的简单调用将声明替换为 t;我想知道这个编译错误是否与 boost 版本有关。如果有任何帮助,我正在使用 Boost ASIO 1.42、Ubuntu 11.04 和 Eclipse。先感谢您。