c++ - 删除后 async_write 会导致段错误吗?

标签 c++ boost segmentation-fault boost-asio

我正在使用 Boost 通过 TCP 发送数据 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;
        }
//....

注意 delete this;在写处理程序中。

所以当发送数据出错时,session会断开连接,然后自行删除。但是,writeHandler 之后出现段错误已经回来了。难道是因为我在删除this尽管它被捕获在 async_write 中?

最佳答案

一旦您删除此,对该对象的任何访问都是无效的。您是否在其他任何地方复制/捕获了指针都没有关系。

关于c++ - 删除后 async_write 会导致段错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526553/

相关文章:

java - 我可以在 C++ 中实现多个回调接口(interface)吗?

c++ - 使用复制构造函数 C++ 时出现段错误

java - 带有长字符串的 protobuf 中的奇怪行为

c++ - 使用 ffmpeg 解码 Wma

带 token 串联的 C++ 宏参数?

c++ - Boost graph typedef c++ 结构的前向声明

c++ - 正确使用 s/rand 或 Boost::random

c++ - 通过自定义边缘权重惩罚来 boost A* 访问者?

c - 二叉树实现在 C 中给我段错误

c++ - 在 C++ 中迭代 std::set<std::string> 时出现段错误