正确的方法来调用boost io_service.post

时间:2012-11-21 09:22:42

标签: c++ multithreading boost boost-asio stdstring

我有以下功能:

void MyLib::sendMessage(const std::string& message) {
  m_xIOService.post( boost::bind(&VoIPPhone::onSendMessage, this, message) );
}

void MyLib::onSendMessage(const std::string& message) {
  m_xVoIPClient.sendMessage(message);
}

所以我在一个线程中调用sendMessage,并在主线程中调用onSendMessage。

问题是在这种情况下是否会通过boost复制消息字符串。如果不是 - 如何将字符串传递给onSendMessage函数并确保没有内存泄漏且消息字符串有效,而不是删除对象?

1 个答案:

答案 0 :(得分:6)

onSendMessage将在其中一个执行m_xIOService::run的线程中调用 - 而不是在主线程中。

复制了所有bind个参数,因此也会复制message。每当您想通过引用传递bind参数时,请使用boost::ref包装器。