nlib
Singleton.h
[詳解]
1 
2 /*--------------------------------------------------------------------------------*
3  Project: CrossRoad
4  Copyright (C)Nintendo All rights reserved.
5 
6  These coded instructions, statements, and computer programs contain proprietary
7  information of Nintendo and/or its licensed developers and are protected by
8  national and international copyright laws. They may not be disclosed to third
9  parties or copied or duplicated in any form, in whole or in part, without the
10  prior written consent of Nintendo.
11 
12  The content herein is highly confidential and should be handled accordingly.
13  *--------------------------------------------------------------------------------*/
14 
15 #pragma once
16 #ifndef INCLUDE_NN_NLIB_SINGLETON_H_
17 #define INCLUDE_NN_NLIB_SINGLETON_H_
18 
19 #include "nn/nlib/Config.h"
20 
21 NLIB_NAMESPACE_BEGIN
22 
23 template <class T>
25  public:
26  static T& Instance() {
27  if (!flag_) {
29  nlib_once(&once_flag_, Init);
30  }
31  T* ptr = reinterpret_cast<T*>(&memory_[0]);
32  return *ptr;
33  }
34  static T& GetInstance() { return Instance(); }
35 
36  private:
37  static void Init();
38  static int32_t flag_;
39  static nlib_onceflag once_flag_;
40  // Memory leak would be mis-detected if dynamically allocated.
41  NLIB_ALIGNAS(8) static unsigned char memory_[sizeof(T)];
42 
43  private:
44  Singleton() {}
46 };
47 
48 template <class T>
49 void Singleton<T>::Init() {
50  new (memory_) T();
52 }
53 
54 template <class T>
56 template <class T>
57 int32_t Singleton<T>::flag_ = 0;
58 template <class T>
59 
60 #ifndef NLIB_DOXYGEN
61 #if !defined(NN_PLATFORM_CTR)
62 NLIB_ALIGNAS(8) unsigned char Singleton<T>::memory_[sizeof(T)];
63 #else
64 unsigned char Singleton<T>::memory_[sizeof(T)];
65 #endif
66 #endif
67 
68 NLIB_NAMESPACE_END
69 
70 #endif // INCLUDE_NN_NLIB_SINGLETON_H_
int32_t nlib_atomic_load32(const int32_t *ptr, int memorder)
アトミックに値をロードします。動作はgccの__atomic_load_n()に準じます。
#define NLIB_DISALLOW_COPY_AND_ASSIGN(TypeName)
TypeName で指定されたクラスのコピーコンストラクタと代入演算子を禁止します。
Definition: Config.h:179
#define NLIB_ATOMIC_RELEASE
gccの__ATOMIC_RELEASEやC++11のstd::memory_order_releaseに準じます。
errno_t nlib_once(nlib_onceflag *flag, nlib_oncefunc func)
func を高々1回しか実行されないようします。
最初に利用されるときにオブジェクトが初期化されるシングルトンです。
Definition: Singleton.h:24
#define NLIB_ATOMIC_ACQUIRE
gccの__ATOMIC_ACQUIREやC++11のstd::memory_order_acquireに準じます。
開発環境別の設定が書かれるファイルです。
#define NLIB_ALIGNAS(x)
alignas(x)又は同等の定義がされます。
Definition: Config.h:255
#define NLIB_ONCE_INIT
nlib_onceflagを静的に初期化するための値
Definition: Platform.h:1128
#define NLIB_FINAL
利用可能であればfinalが定義されます。そうでない場合は空文字列です。
Definition: Config.h:245
struct nlib_onceflag_ nlib_onceflag
nlib_onceで利用される構造体
Definition: Platform.h:1127
static T & Instance()
T のシングルトンインスタンスを取得します。
Definition: Singleton.h:26
void nlib_atomic_store32(int32_t *ptr, int32_t val, int memorder)
アトミックに値をストアします。動作はgccの__atomic_store_n()に準じます。