Note that there are some explanatory texts on larger screens.

plurals
  1. POdeadline_timer callback called on a deleted object
    text
    copied!<p>In the flowing code, even though I inherit net class from boost::enable_shared_from_this, when net get deleted,OnTimer still get called on a invalid object one more time.How to solve this problem? Thanks in advance.</p> <pre><code>boost::shared_ptr&lt;boost::asio::io_service&gt; service = boost::make_shared&lt;boost::asio::io_service&gt;(); class net:public boost::enable_shared_from_this&lt;net&gt; { public: net(boost::shared_ptr&lt;boost::asio::io_service&gt;&amp; service); void StartTimer(); void OnTimer(const boost::system::error_code&amp; e); ~net(); private: boost::asio::deadline_timer timer_; int a; }; net::net(boost::shared_ptr&lt;boost::asio::io_service&gt;&amp; service) :timer_(*service, boost::posix_time::milliseconds(1000)) { } net::~net() { timer_.cancel(); } void net::StartTimer() { timer_.async_wait(boost::bind(&amp;net::OnTimer, shared_from_this(), boost::asio::placeholders::error)); } void net::OnTimer(const boost::system::error_code&amp; e) { a = 10; timer_.async_wait(boost::bind(&amp;net::OnTimer, shared_from_this(), boost::asio::placeholders::error)); } unsigned int WINAPI ThreadMain(void* arg) { boost::shared_ptr&lt;net&gt; ptr(new net(service)); ptr-&gt;StartTimer(); Sleep(5000); boost::shared_ptr&lt;net&gt; invalid_ptr; ptr = invalid_ptr; return 0; } int _tmain(int argc, _TCHAR* argv[]) { boost::shared_ptr&lt;boost::asio::io_service::work&gt; io_service_work = boost::make_shared&lt;boost::asio::io_service::work&gt;(*service); boost::system::error_code ec; HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadMain, NULL, 0, NULL); if (hThread == NULL) { return -1; } boost::shared_ptr&lt;boost::thread&gt; thread_ = boost::make_shared&lt;boost::thread&gt;(boost::bind(&amp;boost::asio::io_service::run, service.get(), ec)); // in order to make sure OnTimer can be called at least once Sleep(2000); boost::shared_ptr&lt;boost::asio::io_service::work&gt; invalid_ptr; io_service_work = invalid_ptr; thread_-&gt;join(); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload