MyGUI  3.2.1
MyGUI_Singleton.h
Go to the documentation of this file.
1 /*
2  * This source file is part of MyGUI. For the latest info, see http://mygui.info/
3  * Distributed under the MIT License
4  * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
5  */
6 
7 #ifndef __MYGUI_SINGLETON_H__
8 #define __MYGUI_SINGLETON_H__
9 
10 #include "MyGUI_Diagnostic.h"
11 
12 namespace MyGUI
13 {
14 
15 #if MYGUI_COMPILER == MYGUI_COMPILER_MSVC || MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
16  template <class T>
17  class Singleton
18 #else
19  template <class T>
21 #endif
22  {
23  public:
24  typedef Singleton<T> Base;
25 
27  {
28  MYGUI_ASSERT(nullptr == msInstance, "Singleton instance " << getClassTypeName() << " already exsist");
29  msInstance = static_cast<T*>(this);
30  }
31 
32  virtual ~Singleton()
33  {
34  MYGUI_ASSERT(nullptr != msInstance, "Destroying Singleton instance " << getClassTypeName() << " before constructing it.");
35  msInstance = nullptr;
36  }
37 
38  static T& getInstance()
39  {
40  MYGUI_ASSERT(nullptr != getInstancePtr(), "Singleton instance " << getClassTypeName() << " was not created");
41  return (*getInstancePtr());
42  }
43 
44  static T* getInstancePtr()
45  {
46  return msInstance;
47  }
48 
49  static const char* getClassTypeName()
50  {
51  return mClassTypeName;
52  }
53 
54  private:
55  static T* msInstance;
56  static const char* mClassTypeName;
57  };
58 
59 } // namespace MyGUI
60 
61 #endif // __MYGUI_SINGLETON_H__