| 1 | #ifndef HL_EXACTLYONE_H |
| 2 | #define HL_EXACTLYONE_H |
| 3 | |
| 4 | /* |
| 5 | |
| 6 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 7 | |
| 8 | Copyright (C) 2000-2020 by Emery Berger |
| 9 | http://www.emeryberger.com |
| 10 | [email protected] |
| 11 | |
| 12 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 13 | |
| 14 | You may obtain a copy of the License at |
| 15 | http://www.apache.org/licenses/LICENSE-2.0 |
| 16 | |
| 17 | */ |
| 18 | |
| 19 | /** |
| 20 | * @class ExactlyOne |
| 21 | * @brief Creates a singleton of type CLASS, accessed through (). |
| 22 | * @author Emery Berger <http://www.emeryberger.org> |
| 23 | */ |
| 24 | |
| 25 | #if defined(__cplusplus) // ignore if not compiling C++ |
| 26 | |
| 27 | #include <new> |
| 28 | |
| 29 | namespace HL { |
| 30 | |
| 31 | template <class CLASS> |
| 32 | class ExactlyOne { |
| 33 | public: |
| 34 | |
| 35 | inline CLASS& operator()() { |
| 36 | // We store the singleton in a double buffer to force alignment. |
| 37 | static double buf[(sizeof(CLASS) + sizeof(double) - 1) / sizeof(double)]; |
| 38 | static CLASS * theOneTrueInstancePtr = new (buf) CLASS; |
| 39 | return *theOneTrueInstancePtr; |
| 40 | } |
| 41 | |
| 42 | }; |
| 43 | |
| 44 | } |
| 45 | |
| 46 | #endif |
| 47 | |
| 48 | #endif |