2017-01-07 47 views
0

我使用升壓通過TCP與async_write發送數據:當這被刪除時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;

因此,當發送數據時發生錯誤時,會話將斷開連接,然後自行刪除。但是,writeHandler已返回後出現分段錯誤。難道是因爲我刪除this,雖然它被捕獲在async_write

+0

我知道,但是我不再在「我的」代碼中訪問它。所以我認爲可以在'writeHandler'返回後通過'async_write'訪問。 – Bobface

回答

1

一旦您delete this對該對象的任何訪問都是無效的。如果您在其他地方複製/捕獲指針,則無關緊要。

+0

我在我的問題下寫了一條回覆您的評論: \t 我知道,但是我不再在「我的」代碼中訪問它。所以我認爲它可能被async_write訪問,writeHandler返回 – Bobface

+1

。 'this'綁定在綁定中:'boost :: bind(&Session :: writeHandler, this'。你正在代碼中訪問它,它會被完成處理程序異步執行,因爲你問了它。在所有樣本中都看到enable_shared_from_this模式。 – sehe