|
| 1 | +#pragma once |
| 2 | +#ifndef INC_SINGLETON_H_ |
| 3 | +#define INC_SINGLETON_H_ |
| 4 | + |
| 5 | +#include <mutex> |
| 6 | +#include <typeindex> |
| 7 | +#include <memory> |
| 8 | +#include "singleton_api.h" |
| 9 | + |
| 10 | +// Singleton mode for cpp |
| 11 | +// |
| 12 | +// Features -- |
| 13 | +// 1. Works for both dynamical library and executable. |
| 14 | +// 2. Multithread safe |
| 15 | +// 3. Lazy consturction |
| 16 | + |
| 17 | +template<typename T> |
| 18 | +class Singleton; |
| 19 | + |
| 20 | +// Get singleton instance |
| 21 | +template<typename T> |
| 22 | +inline T &singleton() { |
| 23 | + return Singleton<T>::getInstance(); |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +struct SingleTonHolder { |
| 28 | + void *object_; |
| 29 | + std::shared_ptr<std::mutex> mutex_; |
| 30 | +}; |
| 31 | + |
| 32 | +SINGLETON_API std::mutex &getSingleTonMutex(); |
| 33 | +SINGLETON_API SingleTonHolder *getSingleTonType(const std::type_index &typeIndex); |
| 34 | + |
| 35 | + |
| 36 | +template<typename T> |
| 37 | +class Singleton { |
| 38 | +public: |
| 39 | + // Get the single instance |
| 40 | + static T &getInstance() { |
| 41 | + return *getInstancePrivate(); |
| 42 | + } |
| 43 | + |
| 44 | +private: |
| 45 | + // Get the single instance |
| 46 | + static T *getInstancePrivate() { |
| 47 | + static T *instance = nullptr; |
| 48 | + if (instance != nullptr) |
| 49 | + return instance; |
| 50 | + |
| 51 | + SingleTonHolder *singleTonHolder = nullptr; |
| 52 | + { |
| 53 | + // Locks and get the global mutex |
| 54 | + std::lock_guard<std::mutex> myLock(getSingleTonMutex()); |
| 55 | + if (instance != nullptr) |
| 56 | + return instance; |
| 57 | + |
| 58 | + singleTonHolder = getSingleTonType(std::type_index(typeid(T))); |
| 59 | + } |
| 60 | + |
| 61 | + // Create single instance |
| 62 | + T *instanceFromHolder = createInstanceFromHolder(singleTonHolder); |
| 63 | + |
| 64 | + { |
| 65 | + // Save single instance object |
| 66 | + std::lock_guard<std::mutex> myLock(getSingleTonMutex()); |
| 67 | + instance = instanceFromHolder; |
| 68 | + return instance; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + static T *createInstanceFromHolder(SingleTonHolder *singleTonHolder) { |
| 73 | + // Locks class T and make sure to call construction only once |
| 74 | + std::lock_guard<std::mutex> myLock(*singleTonHolder->mutex_); |
| 75 | + if (singleTonHolder->object_ == nullptr) { |
| 76 | + // construct the instance with static funciton |
| 77 | + singleTonHolder->object_ = reinterpret_cast<void *>(getStaticInstance()); |
| 78 | + } |
| 79 | + return reinterpret_cast<T *>(singleTonHolder->object_); |
| 80 | + } |
| 81 | + |
| 82 | + static T *getStaticInstance() { |
| 83 | + static T t; |
| 84 | + return &t; |
| 85 | + } |
| 86 | +}; |
| 87 | + |
| 88 | + |
| 89 | +#endif |
0 commit comments