gpt4 book ai didi

c++ - 调用 boost io_service.post 的正确方法

转载 作者:太空狗 更新时间:2023-10-29 20:28:19 24 4
gpt4 key购买 nike

我有以下功能:

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 函数并确保不会发生内存泄漏并且消息字符串有效,而不是已删除的对象?

最佳答案

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

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

关于c++ - 调用 boost io_service.post 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13489958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com