Carna  Version 3.3.2
Singleton.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2010 - 2015 Leonid Kostrykin
3  *
4  * Chair of Medical Engineering (mediTEC)
5  * RWTH Aachen University
6  * Pauwelsstr. 20
7  * 52074 Aachen
8  * Germany
9  *
10  */
11 
12 #ifndef SINGLETON_H_6014714286
13 #define SINGLETON_H_6014714286
14 
20 #include <Carna/base/noncopyable.h>
21 
22 namespace Carna
23 {
24 
25 namespace base
26 {
27 
28 
29 
30 // ----------------------------------------------------------------------------------
31 // Singleton
32 // ----------------------------------------------------------------------------------
33 
58 template< typename InstanceType >
59 class Singleton
60 {
61 
63 
67  static InstanceType* instancePtr;
68 
69 protected:
70 
75  {
76  CARNA_ASSERT_EX( instancePtr == nullptr, "Multiple singleton instances created." );
77  instancePtr = static_cast< InstanceType* >( this );
78  }
79 
83  static void reset()
84  {
85  if( instancePtr != nullptr )
86  {
87  delete instancePtr;
88  }
89  }
90 
91 public:
92 
96  typedef InstanceType Instance;
97 
101  virtual ~Singleton()
102  {
103  instancePtr = nullptr;
104  }
105 
109  static InstanceType& instance()
110  {
111  return instancePtr == nullptr ? *new InstanceType() : *instancePtr;
112  }
113 
117  static bool exists()
118  {
119  return instancePtr != nullptr;
120  }
121 
122 }; // Singleton
123 
124 
125 template< typename InstanceType >
126 InstanceType* Singleton< InstanceType >::instancePtr = nullptr;
127 
128 
129 
130 } // namespace Carna :: base
131 
132 } // namespace Carna
133 
134 #endif // SINGLETON_H_6014714286
static void reset()
Deletes the only instance from class InstanceType.
Definition: Singleton.h:83
Singleton base class
Definition: Singleton.h:59
#define CARNA_ASSERT_EX(expression, description)
If the given expression is false, a break point is raised in debug mode and an AssertionFailure throw...
virtual ~Singleton()
Denotes that the instance was deleted.
Definition: Singleton.h:101
static InstanceType & instance()
Returns the only instance from class InstanceType.
Definition: Singleton.h:109
InstanceType Instance
Denotes the class, that is derived from this class template.
Definition: Singleton.h:96
Singleton()
Denotes that the instance was created. Default constructor is hidden.
Definition: Singleton.h:74
Defines Carna::base::CarnaException, Carna::base::AssertionFailure.
#define NON_COPYABLE
Features class it is placed in as non-copyable.
Definition: noncopyable.h:109
static bool exists()
Tells whether the instance from class InstanceType currently exists.
Definition: Singleton.h:117