c++ - "String iterator not dereferncable" boost async_read_some

标签 c++ boost boost-asio shared-ptr asio

我有一个服务器使用来自 boost 的异步套接字和“接受”函数,如下所示(“用户”几乎等同于 this 示例中的“ session ”):

    accept()
{
    this->_acceptor.async_accept(this->_socket, [this](boost::system::error_code error)
    {
        if (!error)
        {
            make_shared<User>(move(_socket), *this)->read();
        }
        accept();
    });
}

如下所示的“读取”函数(_readData 是一个 1024 的字符数组):

    void User::read()
{
    auto self(shared_from_this());
    this->_socket.async_read_some(boost::asio::buffer(this->_readData, 1024),
        [this, self](boost::system::error_code error, size_t length)
    {
        if (!error)
        {
            this->buildReceivedMessage(string(this->_readData, length));
            this->read();
        }
    });
}

还有一个“写”函数。

当我用客户端连接到服务器时,从客户端到服务器的第一次传输很顺利,服务器按预期发回响应。然后,我一步步往代码里走,读函数执行完后,代码进入了几个我不认识的头文件,最后抛出“Expression: cannot dereference string iterator because the iterator was invalidated (e.g. reallocation occurred) , 或者字符串已被破坏)”断言问题形成了 xstring 文件。对于我的一生,我不知道为什么。

编辑 1: buildReceivedMessage 创建一个 ReceivedMessage,其中包含易于访问格式的请求值,然后将其转发给 messageHandler , 它根据请求的类型转发请求。 例如,第一个请求是登录请求,因此 ReceivedMessage 在此函数中结束:

void User::handleSignin(shared_ptr<ReceivedMessage> msg)
{
    vector<string> values = msg->getValues();
    if (this->_server.getDB().isUserAndPassMatch(values[0], values[1]))
    {
        if (this->getUserByName(values[0]))
        {
            this->write("1022");
        }
        else
        {
            this->_server.addUser(shared_ptr<User>(this));
            this->write("1020");
            this->_username = values[0];
        }
    }
    else
    {
        this->write("1021");
    }
}

最佳答案

在:

void User::read()
{
    auto self(shared_from_this());
    this->_socket.async_read_some(boost::asio::buffer(this->_readData, 1024),
        [this, self](boost::system::error_code error, size_t length)
    {
        if (!error)
        {
            this->buildReceivedMessage(string(this->_readData, length));
            this->read();
        }
    });
}

你依赖于 shared_ptr self 来保持你的连接。这很好,但是 buildReceivedMessage() 是否也为 self 创建了一个 shared_ptr?

handleSignin() 没有收到 shared_ptr,这让我怀疑你的对象 self,也就是 this,真的被销毁了过早地。

我会首先尝试在 User::read() 中使用 self 而不是 this ,以确保捕获 self 不会被优化掉(是的,这是可能的)。我还要确保不要仅仅依靠读取循环来保持连接。

关于c++ - "String iterator not dereferncable" boost async_read_some,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717311/

相关文章:

c++ - 移植项目VS2003 -> VS2013错误C2039 serialize is not member of hash_Map

c++ - 如何知道 Boost asio 中 SSL 套接字的状态

c++ - boost::asio http 服务器无法向 Postman 返回有效响应

c++ - Boost的lexical_cast从double到string的精度

c++ - 4.5 规则 : No move assignment operator?

c++ - CodeEval 挑战 : Reverse strings in input file

c++ - 访问 C 中结构数组中的数组(结构成员)

c++ - 不在 make 过程中命名类型

c++ - 使用 boost::bind 的调用错误没有匹配函数

c++ - OpenCV 中的鸟瞰投影误差