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;
36 }
37 return *instance;
38 }
39
41 [[nodiscard]] static T* handleIfAlive() noexcept {
42 return instance;
43 }
44
46 static void destroy() noexcept {
47 delete instance;
48 instance = nullptr;
49 }
50
51protected:
52 Singleton() = default;
53
54private:
55 static T* instance;
56};
57
58template <class T> T* Singleton<T>::instance = nullptr;
59
60} // 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:41
static void destroy() noexcept
Deletes the Singleton.
Definition Singleton.hpp:46
static T & handle()
Creates the Singleton if needed.
Definition Singleton.hpp:32
JNGL's main namespace.
void atExit(std::function< void()>)
Call this function once when the window is hidden.
Functions related to the main window.