m2etis  0.4
Singleton.h
Go to the documentation of this file.
1 /*
2  Copyright (2016) Michael Baer, Daniel Bonrath, All rights reserved.
3 
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7 
8  http://www.apache.org/licenses/LICENSE-2.0
9 
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15  */
16 
22 #ifndef __M2ETIS_UTIL_SINGLETON_H__
23 #define __M2ETIS_UTIL_SINGLETON_H__
24 
26 
27 #include "boost/interprocess/sync/scoped_lock.hpp"
28 #include "boost/thread.hpp"
29 
30 namespace m2etis {
31 namespace util {
32 
39  template<typename T>
40  class Singleton {
41  public:
42  static inline T * GetSingletonPtr() {
43  Init();
44 
45  return _ptrSingleton;
46  }
47 
48  static inline T & GetSingleton() {
49  Init();
50 
51  return *_ptrSingleton;
52  }
53 
54  protected:
55  Singleton() {}
56  virtual ~Singleton() {
57  boost::unique_lock<boost::mutex> lock(_objMutex);
58  if (_ptrSingleton != NULL) {
59  delete _ptrSingleton;
60  _ptrSingleton = NULL;
61  }
62  }
63  static T * _ptrSingleton;
64  static boost::mutex _objMutex;
65 
66  private:
67  static void Init() {
68  // Double check to avoid overhead locking
69  if (!_ptrSingleton) {
70  // no need to unlock, because the destructor of boost::unique_lock does this for us
71  boost::unique_lock<boost::mutex> lock(_objMutex);
72  if (!_ptrSingleton) {
73  _ptrSingleton = new T();
74  }
75  }
76  }
77 
78  Singleton(const Singleton &) {}
79  const Singleton& operator=(const Singleton &) { return *this; }
80  };
81 
82  template<typename T> T * Singleton<T>::_ptrSingleton = nullptr;
83  template<typename T> boost::mutex Singleton<T>::_objMutex;
84 
85 } /* namespace util */
86 } /* namespace m2etis */
87 
88 #endif /* __M2ETIS_UTIL_SINGLETON_H__ */
89 
static T & GetSingleton()
Definition: Singleton.h:48
static boost::mutex _objMutex
Definition: Singleton.h:64
Derive from this templated class to make a class a singleton. Refer to the Singleton Design Pattern i...
Definition: Singleton.h:40
static T * GetSingletonPtr()
Definition: Singleton.h:42
static T * _ptrSingleton
Definition: Singleton.h:63