Making enterModalState smartpointer friendly

This is a low-priority question to the JUCE masters:

I’m using enterModalState to avoid modal loops and I stumbled across an issue that probably will cause trouble to other people too.

void Component::enterModalState (bool shouldTakeKeyboardFocus,
ModalComponentManager::Callback* callback,
bool deleteWhenDismissed)

If the Component is defined with a smartpointer, when deleteWhenDismissed is true the object is deleted without letting the smartpointer know.

It is not a big problem, you can delete the component using the smartpointer at the end of the callback but it’s an easy one to miss.

Is there a way to fix that adding maybe some dynamic_casts to unique_ptr or shared_ptr inside enterModalState to cover at least the most common cases?

Given that that argument defaults to false anyway, I don’t see much use in adding explicit support for smart pointers? If you instantiated your component with a std::unique_ptr, why would you pass true to the deleteWhenDismissed argument?

If you used juce::Component::SafePointer, you would get the behaviour you expect as SafePointer will detect when the object is deleted and make itself nullptr accordingly.

Where are you seeing that? a juce::Component::SafePointer is a wrapper for juce::WeakReference<juce::Component>. It’s basically the same behaviour as a std::weak_ptr. A std::unique_ptr would have very different behaviour. Unless I’m missing something?

Hi Anthony and ImJimmi, thank you for your answers. You are right. I’ve checked again and I can’t understand why I saw that. I will try with juce::Component::SafePointer.

It’s a bit off-topic, but for completeness sake the difference between juce::WeakReference and std::weak_ptr is that the std::weak_ptr can be made thread safe because it can be turned into a std::shared_ptr:

auto safePtr = weakPtr.lock(); // returns a std::shared_ptr that will make sure the object stays alive

With WeakReference:

if (weakReference)
    weakReference->foo(); // could get deleted while being used

I know that you are probably aware @anthony-nicholls , just an addition for the readers


@Daniel thanks, definitely worth highlighting as I just brushed it away by saying basically the same.

1 Like