I am using Boost to send data over TCP with async_write
:
std::shared_ptr<std::vector<std::string>::iterator> iter = std::make_shared<std::vector<std::string>::iterator>(this->m_vDataToWrite.begin());
boost::asio::async_write(this->socket_, boost::asio::buffer(*message),
boost::asio::transfer_all(), boost::bind(&Session::writeHandler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred(),
message,
iter
));
// ...
void Session::writeHandler(const boost::system::error_code &error, std::size_t bytes_transferred, std::shared_ptr<std::string> message, std::shared_ptr<std::vector<std::string>::iterator> it)
{
if(error)
{
std::cout << "Write handler error: " << error.message() << std::endl;
this->disconnect();
delete this;
return;
}
//....
Notice the delete this;
in the write handler.
So when there is an error while sending the data, the session will disconnect and then delete itself. However, there is a segmentation fault after writeHandler
has returned. Could it be because I am deleting this
although it is captured in async_write
?
Once you delete this
any access to the object is invalid. It doesn't matter if you've copied/captured the pointer anywhere else.
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.