我正在使用Boost Asio库。我在使用boost::async_read()操作时遇到困难。我正在这样使用。下面给出了服务器asio读取操作的示例代码。
void HandleClient::StartHandling()
{
auto self(shared_from_this());
asio::async_read_until(m_Sock,
m_Request,
DELIMITER,
[this, self](
const boost::system::error_code& a_Ec,
std::size_t a_BytesRead)
{
onRequestReceived(a_Ec, a_BytesRead);
});
}
void HandleClient::onRequestReceived(const system::error_code &a_Ec,
std::size_t a_BytesRead)
{
if(a_Ec)
{....}
auto self(shared_from_this());
if(a_BytesRead > 0)
{
auto response = ProcessData(m_Request);
if(!response.empty())
{
m_Data = response + DELIMITER;
asio::async_write(m_Sock, asio::buffer(m_Data),
[this, self](boost::system::error_code& a_Ec, std::size_t
a_Bytestransferred))
{
response_sent(a_Ec, a_Bytestransferred);
});
}
asio::async_read_until(
m_Sock,
m_Request,
DELIMITER,
[this, self](const boost::system::error_code& a_Ec, std::size_t
a_BytesRead)
{
onRequestReceived(a_Ec, a_BytesRead);
});
}
经过一番迭代,它变得崩溃了。崩溃是随机的。客户端代码采用同步调用的形式。我希望这不是问题。我收到调试断言失败消息的错误消息:Debug assertion failed Program:xx/vc/tools/msvc/14.16.27023/include/xstring Line 1427. Expression cannot deference string iteration because the iterator was invalidated (e.g. reallocation occurred, or the string was destroyed)
最佳答案
我们不知道事物的生命是什么。
如果我们假设m_Data
是std::string
,它是使用std::enable_shared_from_this
的类的成员,则对明显的错字取模:
auto self(shared_from_this));
看起来一生应该没事。但是,由于您似乎没有在响应缓冲区(m_Data
?)方面进行任何同步,因此可以想象下一个onRequestReceived
最终再次调用相同的代码,可能会在上一个响应之前用新响应覆盖m_Data
。是完全写的。从显示为例如
response
和m_Data
似乎没有任何明确的关系:auto response = ProcessData(m_Request);
asio::async_write(m_Sock, asio::buffer(m_Data),
// where did `m_Data` come
// from?!
// response **looks** like a local variable which
// is dangerous in async code (of course it might
// be a [smart] pointer or something, but we can't
// tell
总结观察结果:response_sent
时)。 另请参阅:Why do I need strand per connection when using boost::asio?
关于c++ - Boost Asio异步操作调试断言问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63380319/