简体   繁体   English

使用BOOST ASIO在异步服务器中发送局部变量

[英]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. 您需要分配堆的数据并在回调中释放它,或使用某种结构来自动释放其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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