Colobot
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
singleton.h
Go to the documentation of this file.
1 // * This file is part of the COLOBOT source code
2 // * Copyright (C) 2012, Polish Portal of Colobot (PPC)
3 // *
4 // * This program is free software: you can redistribute it and/or modify
5 // * it under the terms of the GNU General Public License as published by
6 // * the Free Software Foundation, either version 3 of the License, or
7 // * (at your option) any later version.
8 // *
9 // * This program is distributed in the hope that it will be useful,
10 // * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // * GNU General Public License for more details.
13 // *
14 // * You should have received a copy of the GNU General Public License
15 // * along with this program. If not, see http://www.gnu.org/licenses/.
16 
22 #pragma once
23 
24 #include <cassert>
25 
26 
27 template<typename T> class CSingleton
28 {
29 protected:
30  static T* m_instance;
31 
32 public:
33  static T& GetInstance()
34  {
35  assert(m_instance != nullptr);
36  return *m_instance;
37  }
38 
39  static T* GetInstancePointer()
40  {
41  assert(m_instance != nullptr);
42  return m_instance;
43  }
44 
45  static bool IsCreated()
46  {
47  return m_instance != nullptr;
48  }
49 
50  CSingleton()
51  {
52  assert(m_instance == nullptr);
53  m_instance = static_cast<T *>(this);
54  }
55 
56  virtual ~CSingleton()
57  {
58  m_instance = nullptr;
59  }
60 
61  #ifdef TESTS
62  static void ReplaceInstance(T* newInstance)
63  {
64  assert(newInstance != nullptr);
65 
66  if (m_instance != nullptr)
67  delete m_instance;
68 
69  m_instance = newInstance;
70  }
71  #endif
72 
73 private:
74  CSingleton& operator=(const CSingleton<T> &);
75  CSingleton(const CSingleton<T> &);
76 };
77 
Definition: singleton.h:27