Is SafePointer required with FileChooser launchAsync?

I have a unique_ptr onto a FileChooser as a member of my class.
I use launchAsync with a lambda.
Can i safely capture this in it (i.e. is the dialog guaranted to be aborted first when my class is deleted), or do i have to use a SafePointer (or something like that)?
I guess that this is safe, but i’m not 100% sure when reading the documentation.

When calling async functions, it’s always a good idea to capture your components in Component::SafePointer<T> objects, and then check in the lambda if they’re still valid:

button.onClick = [safePtr = Component::SafePointer<Editor>(this)]()
    if( auto* editor = safePtr.getComponent() )
        //make the editor respond accordingly when the button is clicked

If you look inside a lot of the Button/Slider/ComboBox class implementations, you’ll see that a similar BailOutChecker is used to check if the object being used has been deleted by the callback inadvertently.

1 Like

In general yes but…

In that case it seems that the callback is cleared when the FileChooser is deleted. It seems also that the dialog is disposed before (at least with FileChooser::Native on macOS). And reading the JUCE sources a bit more deeply it appears, that the dialog MUST be canceled before to call the finished method. Otherwise a dangling reference to owning FileChooser would be used.

Thus IMHO capture this is perfectly safe (and SafePointer is not required). It is what i deduced also reading “To abort the file selection, simply delete the FileChooser object.” inside the documentation. Please anybody correct me if i’m wrong and/or tell me if it is guaranteed to remain true in the futur.

Anyway you are right, i could use a SafePointer to preclude bugs in case of implementation changes.

There’s no point trying to justify potentially unsafe behavior when safe behavior only adds a few lines of code! I recommend you stick with using a SafePointer<Editor>. You can make one a member variable and capture it by copy in your lambda so you only have to type the creation of one exactly once.


“To abort file selection, simply delete the FileChooser object”.
This tells me that the callback should never happen after deleting the FileChooser object (following RAII principles). Capturing this should be perfectly safe.

My preference is to write shortest code as possible so I would not add the SafePointer thing but obviously it does no harm to add it.

1 Like

As far as I am concerned i prefer to spend time to analyze precisely what is safe and what is unsafe and use the appropriate tools. Potentially unsafe is a strange thing for me. :grinning_face_with_smiling_eyes: