Skip to content

Instantly share code, notes, and snippets.

@fcamel
Last active October 1, 2016 17:54
Show Gist options
  • Save fcamel/520ebb4f87073a5b5ac0821cdb5b104c to your computer and use it in GitHub Desktop.
Save fcamel/520ebb4f87073a5b5ac0821cdb5b104c to your computer and use it in GitHub Desktop.
Object managed by unique_ptr and run in only one MessageLoop
// Public method.
void Object::DeleteThis()
{
// From now on, all methods will act like NOP.
m_deleted = true;
// Post a new task to run DoDeleteThis().
// We cannot delete |this| right now because |this| may be in m_messageLoop.
m_messageLoop->PostTask(...);
}
// Public method.
bool Object::IsDeleted() const
{
return m_deleted;
}
// Private method.
// Only be called from DeleteThis().
void Object::DoDeleteThis()
{
// It's safe to delete |this| now.
delete this;
}
// All methods should check m_deleted at first.
void Object::Foo()
{
if (m_deleted)
return;
// Do the things.
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment