Home > Mobile >  Static pointer to a class method, if possible and meaningful
Static pointer to a class method, if possible and meaningful

Time:09-28

Usually for singleton classes, one has to write all the time something like this:

SomeSingleton::GetInstance().someVariable

And I'm looking for a simplification that can be seen everywhere, so should be put in the (header and source) files of the class itself.

So, the (non-working) stuff should look something like this:

SomeSingleton.hpp:

class SomeSingleton {
//...
    static SomeSingleton& GetInstance();
};

SomeSingleton& (*INSTANCE)();

SomeSingleton.cpp:

SomeSingleton& (* INSTANCE)() = SomeSingleton::GetInstance;

But this is misinterpreted as a redefinition, so doesn't work. If the declaration and the definition was in the same row, that would work, but then it would not work in a header used from everywhere. Assigning the pointer to the already declared INSTANCE variable wouldn't be simpler than simply defining the INSTANCE every file it is used in.

A workaround is to put a line

static SomeSingleton& (*INSTANCE)() = SomeSingleton::GetInstance;

into every file I use this and replace every SomeSingleton::GetInstance to INSTANCE which works but not ideal plus I'm not sure that from a design aspect it is clever to assign a singleton to a static variable (in a sense a static stuff to another static stuff).

Any ideas on this?

CodePudding user response:

I think the only thing you are missing is extern in your header

extern SomeSingleton& (*INSTANCE)();

CodePudding user response:

I usually try to make designs without singletons (and use dependency injection), which is better for unit testability. But when really needed I use this pattern. You should also read up on Meyer's singleton pattern.

// header file 
struct SomeSingleton
{
    int value{ 42 };
};

SomeSingleton& GetGlobalInstance();

// cpp file

SomeSingleton& GetGlobalInstance()
{
    static SomeSingleton data;
    return data;
}

// some other cpp file
int main()
{
    return GetGlobalInstance().value;
}
  • Related