Skip to content

Instantly share code, notes, and snippets.

@George3d6
Last active September 18, 2018 21:23
Show Gist options
  • Save George3d6/1a508d0155525008bd28a66dc5144d76 to your computer and use it in GitHub Desktop.
Save George3d6/1a508d0155525008bd28a66dc5144d76 to your computer and use it in GitHub Desktop.
//Return a weak pointer, this resource is shared but whoever gets it shouldn't own it
weak_ptr get_widget();
void use_widget() {
auto widget_weak_ptr = get_widget();
//Check if the underylingwidget has already been destroyed.
if(auto widget_ptr = widget_weak_ptr.lock()) {
//If it's available to use create a shared pointer
//When we are done, it's destroyed and we loss shared ownership
widget_ptr->lock_widget_mutex();
if(widget_ptr->get_status() == 42)
widget_ptr->trigger_event();
widget_ptr->unlock_widget_mutex();
//Once the smart pointer is gone we still have the weak pointer left,
//in case we to try and access the widget again in the future
} else {
panic("Widget unavailable");
//Move forward by handling the error or throw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment