Dhia Hassen Dhia Hassen - 1 month ago 10
C++ Question

is there anything wrong with this Singleton class

Under these condition i wrote the next Singleton class :

1 - i want one and only one instance of the class to be present and to be accessible from the whole game engine .

2 - the Singleton is intensively used ( thousands times per frame) so i dont want to write an extra GetInstance() function , im trying to avoid any extra function call for performance

3 - one possibility is to let the GetInstance() be inlined like this :

inline Singleton* Singleton::GetInstance()
{
static Singleton * singleton = new Singleton();
return singleton;
}


but that will cause a reference problem , on each call there will be a new reference to the singleton , to fix that wrote in c++ :

class Singleton{
private:
static Singleton* singleton;
Singleton(){}

public:
static inline Singleton* GetInstance() // now can be inlined !
{
return singleton;
}

static void Init()
{
// ofc i have to check first if this function
// is active only once
if(singleton != nullptr)
{
delete singleton;
}

singleton = new Singleton();
}

~Singleton(){} // not virtual because this class can't be inherited
};

Singleton* Singleton::singleton = nullptr;


What are the possible problems i can face with this implementation ?

Answer

Simply use Meyers' singleton:

class Singleton{
private:
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton operator&(const Singleton&) = delete;

public:
    static Singleton& GetInstance()
    {
        static Singleton instance;
        return instance;
    }
};
Comments