Having throughly blasted my foot with bullets I'm removing all the modal loops from an application.
There's a scenario I'm still scratching my head about though. In the code below if the object I'm calling the AlertWindow from is deleted before the user pushes a button on the dialog, what's the tidiest way of ensuring the callback doesn't crash (as devices will have been deleted). Do I need to use WeakReference here, or is there a less verbose solution I've missed?
I guess I could extend my ModalCallbackAction class to take a WeakReference to the originating object and then not call the lambda at all - which is a relatively nice solution.
auto callback = [this, deviceId](int r) { if (r == 1) { auto newDevice = devices.createNewObject(); newDevice->setUniqueDeviceId(deviceId); newDevice->setConnected(true); listeners.call(&Listener::deviceListChanged); } }; AlertWindow::showOkCancelBox(AlertWindow::QuestionIcon, "Attach Device", "Attach?", "Yes", "No", nullptr, new ModalCallbackAction(callback));
Where:
class ModalCallbackAction : public ModalComponentManager::Callback { public: ModalCallbackAction(std::function<void(int)> actionToRun) : action(actionToRun) {} void modalStateFinished(int resultCode) override { action(resultCode); } private: std::function<void(int)> action; };