| 1 | // -*- C++ -*- |
| 2 | |
| 3 | #ifndef HL_SINGLETON_H |
| 4 | #define HL_SINGLETON_H |
| 5 | |
| 6 | #include <new> |
| 7 | |
| 8 | namespace HL { |
| 9 | |
| 10 | template <class C> |
| 11 | class singleton { |
| 12 | public: |
| 13 | |
| 14 | static C& getInstance() { |
| 15 | #if 0 |
| 16 | static C theSingleton; |
| 17 | return theSingleton; |
| 18 | #else |
| 19 | // This is used with heaps, and when a heap replaces the system heap it needs |
| 20 | // to continue existing past global destructor invocation, as it may be called |
| 21 | // from atexit(), etc. |
| 22 | alignas(std::max_align_t) static char buf[sizeof(C)]; |
| 23 | static C * theSingleton = new (buf) C; |
| 24 | return *theSingleton; |
| 25 | #endif |
| 26 | } |
| 27 | |
| 28 | singleton()= default; |
| 29 | ~singleton()= default; |
| 30 | singleton(const singleton&)= delete; |
| 31 | singleton& operator=(const singleton&)= delete; |
| 32 | }; |
| 33 | |
| 34 | } |
| 35 | |
| 36 | #endif |
| 37 |