简体   繁体   中英

Sending local variable in asynchronous server using BOOST ASIO

Is it propertly way of sending asynchronous local variable ? Won't it will be freed after reaching of function end ? For example :

NET3_SERVER_DISCONNECT data;
    data.mLength = 9;
    data.mPacketGroup = 3;
    data.mPacketType = 100;
    data.mType = 0xcb;
                    boost::asio::async_write(socket_, boost::asio::buffer((char*)&data, sizeof(data)),
                        boost::bind(&Connection::handle_write, shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred));

Thanks.

You are correct.

As the sending is asynchronous, the function where the local variable is defined may return before the data is actually sent, meaning the pointer to it is no longer valid. This leads to undefined behavior .

You need to either allocate the data of the heap and free it in the callback, or use some structure that free its content automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM