nlib
Singleton.h
Go to the documentation of this file.
1 
2 #pragma once
3 #ifndef INCLUDE_NN_NLIB_SINGLETON_H_
4 #define INCLUDE_NN_NLIB_SINGLETON_H_
5 
6 #include "nn/nlib/Config.h"
7 
8 NLIB_NAMESPACE_BEGIN
9 
10 template <class T>
12  public:
13  static T& Instance() {
14  if (!m_Flag) {
16  nlib_once(&m_OnceFlag, Init);
17  }
18  T* ptr = reinterpret_cast<T*>(&m_Memory[0]);
19  return *ptr;
20  }
21  static T& GetInstance() { return Instance(); }
22 
23  private:
24  static void Init();
25  static int32_t m_Flag;
26  static nlib_onceflag m_OnceFlag;
27  // Memory leak would be mis-detected if dynamically allocated.
28  NLIB_ALIGNAS(8) static unsigned char m_Memory[sizeof(T)];
29 
30  private:
31  Singleton() {}
33 };
34 
35 template <class T>
36 void Singleton<T>::Init() {
37  new (m_Memory) T();
39 }
40 
41 template <class T>
42 nlib_onceflag Singleton<T>::m_OnceFlag = NLIB_ONCE_INIT;
43 template <class T>
44 int32_t Singleton<T>::m_Flag = 0;
45 template <class T>
46 
47 #ifndef NLIB_DOXYGEN
48 #if !defined(NN_PLATFORM_CTR)
49 NLIB_ALIGNAS(8) unsigned char Singleton<T>::m_Memory[sizeof(T)];
50 #else
51 unsigned char Singleton<T>::m_Memory[sizeof(T)];
52 #endif
53 #endif
54 
55 NLIB_NAMESPACE_END
56 
57 #endif // INCLUDE_NN_NLIB_SINGLETON_H_
int32_t nlib_atomic_load32(const int32_t *ptr, int memorder)
Loads a value in an atomic operation. Its behavior is similar to the one for __atomic_load_n() of gcc...
#define NLIB_FINAL
Defines final if it is available for use. If not, holds an empty string.
#define NLIB_DISALLOW_COPY_AND_ASSIGN(TypeName)
Prohibits use of the copy constructor and assignment operator for the class specified by TypeName...
Definition: Config.h:126
#define NLIB_ATOMIC_RELEASE
Similar to __ATOMIC_RELEASE of gcc or std::memory_order_release of C++11.
errno_t nlib_once(nlib_onceflag *flag, nlib_oncefunc func)
Ensures that func is executed only one time at most.
Singleton initialized by the object when first used.
Definition: Singleton.h:11
A file that contains the configuration information for each development environment.
#define NLIB_ATOMIC_ACQUIRE
Similar to __ATOMIC_ACQUIRE of gcc or std::memory_order_acquire of C++11.
#define NLIB_ALIGNAS(x)
Defines alignas(x) or the equivalent.
Definition: Config.h:209
#define NLIB_ONCE_INIT
The value for statically initializing nlib_onceflag.
Definition: Platform.h:768
struct nlib_onceflag_ nlib_onceflag
The structure to use with nlib_once.
Definition: Platform.h:767
static T & Instance()
Gets the singleton instance of T.
Definition: Singleton.h:13
void nlib_atomic_store32(int32_t *ptr, int32_t val, int memorder)
Stores a value in an atomic operation. Its behavior is similar to the one for __atomic_store_n() of g...