Josh Elias
Josh Elias

Reputation: 3300

Static Singleton?

Is it possible to make a generic singleton? I want to create something I can just inherit from and get the functionality of a singleton. I'm having trouble with using templates with static members.

Shouldn't this work?

**

UPDATED

**

Thanks for the replies so far. So now my problem is that GameEngine can't see it's own constructor. I know it's private but still.

Singleton.h

template <typename T>
class Singleton
{
private:
    static std::shared_ptr<T> m_Instance;
public: 
    static std::shared_ptr<T> Instance();
};

template<typename T>
std::shared_ptr<T> Singleton<T>::m_Instance = nullptr;

template<typename T>
std::shared_ptr<T> Singleton<T>::Instance()
{
if(m_Instance == nullptr)
    m_Instance = std::make_shared<T>();

return m_Instance;
}

GameEngine.h

class GameEngine : public Singleton<GameEngine>
{
private:
GameEngine();

};

Upvotes: 1

Views: 205

Answers (2)

Andrew Tomazos
Andrew Tomazos

Reputation: 68738

The best way to create a singleton is as follows:

class GameEngine
{
public:
    static GameEngine& instance() { static GameEngine e; return e; }

private:
    GameEngine() {}
    GameEngine(const GameEngine&) = delete;
};

The e variable will be (thread-safely) initialized on first call to instance, and it will be destroyed on orderly process exit. The private/deleted constructors prevent a second instance from ever being created.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258678

I don't see how that'd work, since there's nothing preventing you from creating more instances of GameEngine.

Even if it were possible (and it is) to have a generic way of creating a singleton (perhaps involving macros), I would advise against it, because situations where you actually want singletons are rare. Let me rephrase that... situations where you actually really need a singleton are rare.

Upvotes: 6

Related Questions