1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
26 * Mixin class for "pseudo" singletons.
28 * Classes inheriting from this mixin become "pseudo" singletons that can still be constructed
29 * and destroyed in a controlled manner, but also gain an instance() method for static access.
30 * This is very similar to the behavior of e.g. QCoreApplication.
32 * The mixin protects against multiple instantiation, use-before-instantiation and use-after-destruction
33 * by aborting the program. This is intended to find lifetime issues during development; abort()
34 * produces a backtrace that makes it easy to find the culprit.
36 * The Curiously Recurring Template Pattern (CRTP) is used for the mixin to be able to provide a
37 * correctly typed instance pointer.
44 * Constructs the mixin.
46 * The constructor can only be called once; subsequent invocations abort the program.
48 * @param instance Pointer to the instance being created, i.e. the 'this' pointer of the parent class
50 Singleton(T *instance)
53 qFatal("Trying to reinstantiate a destroyed singleton, this must not happen!");
54 abort(); // This produces a backtrace, which is highly useful for finding the culprit
57 qFatal("Trying to reinstantiate a singleton that is already instantiated, this must not happen!");
63 // Satisfy Rule of Five
64 Singleton(const Singleton &) = delete;
65 Singleton(Singleton &&) = delete;
66 Singleton &operator=(const Singleton &) = delete;
67 Singleton &operator=(Singleton &&) = delete;
72 * Sets the instance pointer to null and flags the destruction, so a subsequent reinstantiation will fail.
81 * Accesses the instance pointer.
83 * If the singleton hasn't been instantiated yet, the program is aborted. No lazy instantiation takes place,
84 * because the singleton's lifetime shall be explicitly controlled.
86 * @returns A pointer to the instance
93 qFatal("Trying to access a singleton that has not been instantiated yet");
99 static bool _destroyed;
104 T *Singleton<T>::_instance{nullptr};
107 bool Singleton<T>::_destroyed{false};