mardi 24 mai 2016

Why android singleton class used a local variable 'instance' instead of using 'sInstance' directly?

The Android Singleton class is defined as follows:

template <typename TYPE>
class Singleton
{
public:
    static TYPE& getInstance() {
        Mutex::Autolock _l(sLock);
        TYPE* instance = sInstance;
        if (instance == 0) {
            instance = new TYPE();
            sInstance = instance;
        }
        return *instance;
    }

protected:
    ~Singleton() { };
    Singleton() { };

private:
    Singleton(const Singleton&);
    Singleton& operator = (const Singleton&);
    static Mutex sLock;
    static TYPE* sInstance;
};

In getInstance(), why using local variable instance instead of just

static TYPE& getInstance() {
    Mutex::Autolock _l(sLock);
    if (sInstance == 0) {
        sInstance = new TYPE();
    }
    return *sInstance;
}

Is this for optimization? and how much difference can this make?

Aucun commentaire:

Enregistrer un commentaire