Singletons and DeletedAtShutdown


Hello !

In the context of an audio plugin, a singleton has to be deleted at shutdown,
for that purpose, Juce addresses both implementation of singletons and objects deleted at shutdown:

  • the DeletedAtShutdown class insures that an object is destroyed when all the active plugin instances have been deleted
  • a set of defines for Singleton helps implement and declare singleton objects

Unfortunately, there is a kind of synchronization loss between these two solutions because they both hold references to the same object.
This synchronization issue is solved by the invocation of clearSingletonInstance() in the destructor of the “singletonized” object.
Thus when using a DeletedAtShutdown singleton, you must invoke clearSingletonInstance in its destructor. If you don’t then you may have some bugs.
First, I think that this constraint is pretty annoying because one may simply forget to add this statement. Secondly, in terms of software design, I think that invoking static stuff in instance-related implementation is not a good thing.

To address this issue, I suggest to separate singleton holding and implementation of the singleton itself. A SingletonHolder template would be in charge of holding singleton instance and inheriting DeletedAtShutdown, so clearing singleton instance at shutdown:

template < class T >
class SingletonHolder : public DeletedAtShutdon
    virtual ~SingletonHolder() {

    // singleton implementation
    static T * instance;

    static T * getInstance();
    static void clearSingletonInstance();

I have not tried this solution and the first difficulty I foresee is that the singletonized class must have a private constructor, so how SingletonHolder will access it ? friend class (personally, I don’t like it) or provide Factory mechanism…

Usage of such a class would be:




In a plugin I don’t recommend using any kind of singleton - if you really need to share objects between your plugin instances, it’s much better to make them reference counted.


Indeed, I need to share object between multiple plugin instances.
How reference counted objects will help me implement shared objects ?


Well, each instance will keep a ref-counted pointer to the object, so it will be deleted when they all close.


thanks for your help
I understand how reference counting helps destroy objects when it is necessary.
However, I don’t how to insure that a single instance of an object will be created, except using singletons.

Anyway I solved this my own way.