Boost ASIO async_write “Vector iterator not dereferencable”

拜拜、爱过 提交于 2019-12-06 09:09:30

问题


I've been working on an async boost server program, and so far I've got it to connect. However I'm now getting a "Vector iterator not dereferencable" error.

I suspect the vector gets destroyed or dereferenced before he packet gets sent thus causing the error.

void start()
{
    Packet packet;
    packet.setOpcode(SMSG_PING);
    send(packet);
}

void send(Packet packet)
{
    cout << "DEBUG> Transferring packet with opcode " << packet.GetOpcode() << endl;
    async_write(m_socket, buffer(packet.write()), boost::bind(&Session::writeHandler, shared_from_this(), placeholders::error, placeholders::bytes_transferred));
}

void writeHandler(const boost::system::error_code& errorCode, size_t bytesTransferred)
{
    cout << "DEBUG> Transfered " << bytesTransferred << " bytes to " << m_socket.remote_endpoint().address().to_string() << endl;
}

Start gets called once a connection is made. packet.write() returns a uint8_t vector

Would it matter if I'd change

void send(Packet packet)

to

void send(Packet& packet)

Not in relation to this problem but performance wise.


回答1:


All this depends on how your Packet class is implemented. How it is copied, .... Has the copy of Packet class do a deep copy or just a default copy? if it is a default copy and your class Packet is not a POD, this can be the reason, and you will need to do a deep copy.

In general it is better to pass a class parameter by const& so maybe you should try with

void send(Packet const& packet);



回答2:


I have found a solution, as the vector would get destroyed I made a queue that contains the resulting packets and they get processed one by one, now nothing gets dereferenced so the problem is solved.

might want to change my queue to hold the packet class instead of the result but that's just a detail.



来源:https://stackoverflow.com/questions/2747891/boost-asio-async-write-vector-iterator-not-dereferencable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!