UndoManager is leaking OwnedArrays?

I have a desktop JUCE application that uses a subclass of UndoManager to handle undo/redo functionality across the app. This works fine, but upon exiting the app I get a JUCE LeakDetector exception saying that between 2-6 instances of OwnedArray have been leaked.
The UndoManager subclass is implemented as a ‘magic static’ singleton, the constructor is private and everything that takes an UndoManager pointer throughout the app accesses it like so:

// == in the header within the RUndoManager class
static UndoManager* get();
//== in the .cpp file
UndoManager* RUndoManager::get()
    static RUndoManager manager;
    return &mananger;

Is there something that needs to be handled in a custom destructor for this to get cleaned up correctly? I don’t know where the particular leaked OwnedArray instances are coming from, so I guess it must be something internal to the UndoManager instance? Any help appreciated!

static variables are not automatically destroyed, so your code is indeed leaking the whole UndoManager.

I would recommend to avoid the static variable.
If you must, you can use juce’s JUCE_DECLARE_SINGLETON macro.

The DeletedAtShutdown might also be useful.

1 Like

Thanks, the JUCE_DECLARE_SINGLETON macro did the trick

I wouldn’t say that is entirely correct. Static objects are indeed destroyed at program exit (their destructors being called). However this might be right after juce leak detector have had it’s round so it may seem to the leak detector there has been some leak, but that’s a false alarm.

But that doesn’t mean its a bad idea to use a singleton.

1 Like