How to create a singleton

The CCoeStatic class allows singleton classes to be created and stored by the environment (CCoeEnv) in Thread Local Storage (TLS). This provides a means of creating writeable global static data.

MySingleton.h

class CMySingleton : public CCoeStatic
    {
public:
    static CMySingleton* SelfL() ;                // Slightly slower
    static CMySingleton* SelfL( CCoeEnv* aCoeEnv ) ;    // Slightly faster
    ...
private:
    CMySingleton() ;
    ~CMySingleton() ;
    } ;

MySingleton.cpp

const TUid KUidMySingleton = {0x10204232} ;

CMySingleton::CMySingleton() : CCoeStatic( KUidMySingleton, CCoeStatic::EThread /*or EApp*/ )
    {
    }

CMySingleton* CMySingleton::SelfL()
    {
    CMySingleton* self = static_cast<CMySingleton*>( CCoeStatic::Static( KUidMySingleton ) ) ; 
    if(!self)
        {
        self = new( ELeave ) CMySingleton() ;
        }
    return self ;
    }

CMySingleton* CMySingleton::SelfL( CCoeEnv* aCoeEnv )
    {
    CMySingleton* self = static_cast<CMySingleton*>( aCoeEnv->FindStatic( KUidMySingleton ) ) ;
    if( !self )
        {
        self = new( ELeave ) CMySingleton() ;
        }
    return self ;
    }

A singleton must be given a UID. When it is instantiated for the first time the base class constructor adds it to the list of singletons in the environment. Any subsequent attempts to instantiate the same singleton will result in a panic.

Singletons may be given a destruction priority and a scope.

The destruction priority determines when the singleton is destroyed relative to any other singletons in the environment's list and relative to the App Ui. The default priority, EDefaultDestructionPriority, is 100. The higher the priority, the earlier the singleton will be destroyed. A negative value indicates that the singleton should be destroyed after the AppUi. The more negative the value, the later the destruction.

The scope may be EThread (the default) or EApp and determines the visibility of the singleton.

Once a singleton has been created it may be accessed through the CCoeEnv API.

// Singleton access
IMPORT_C static CCoeStatic* Static( TUid aUid ) ;
IMPORT_C CCoeStatic* FindStatic( TUid aUid ) ;