JNGL
Easy to use cross-platform 2D game library
Loading...
Searching...
No Matches
Singleton.hpp
Go to the documentation of this file.
1// Copyright 2022-2024 Jan Niklas Hasse <jhasse@bixense.com>
2// For conditions of distribution and use, see copyright notice in LICENSE.txt
5#pragma once
6
7#include "window.hpp"
8
9namespace jngl {
10
23template <class T> class Singleton {
24public:
25 ~Singleton() = default;
26 Singleton(const Singleton&) = delete;
27 Singleton& operator=(const Singleton&) = delete;
28 Singleton(Singleton&&) = delete;
29 Singleton& operator=(Singleton&&) = delete;
30
32 static T& handle() {
33 if (!instance) {
34 instance = new T;
35 atExit([]() {
36 delete instance;
37 instance = nullptr;
38 });
39 }
40 return *instance;
41 }
42
44 [[nodiscard]] static T* handleIfAlive() noexcept {
45 return instance;
46 }
47
48protected:
49 Singleton() = default;
50
51private:
52 static T* instance;
53};
54
55template <class T> T* Singleton<T>::instance = nullptr;
56
57} // namespace jngl
Inherit from this class to create a singleton that will be destroyed when your games exits.
Definition: Singleton.hpp:23
static T * handleIfAlive() noexcept
Doesn't create the Singleton, may return nullptr.
Definition: Singleton.hpp:44
static T & handle()
Creates the Singleton if needed.
Definition: Singleton.hpp:32
JNGL's main namespace.
Definition: Achievement.hpp:10
void atExit(std::function< void()>)
Call this function once when the window is hidden.
Functions related to the main window.