Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
singleton.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Roc authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/target_libuv/roc_core/singleton.h
10 //! @brief Singleton.
11 
12 #ifndef ROC_CORE_SINGLETON_H_
13 #define ROC_CORE_SINGLETON_H_
14 
15 #include <uv.h>
16 
17 #include "roc_core/alignment.h"
18 #include "roc_core/errno_to_str.h"
19 #include "roc_core/noncopyable.h"
20 #include "roc_core/panic.h"
21 
22 namespace roc {
23 namespace core {
24 
25 //! Singleton.
26 template <class T> class Singleton : public core::NonCopyable<> {
27 public:
28  //! Get singleton instance.
29  static T& instance() {
30  uv_once(&once_, create_);
31  return *instance_;
32  }
33 
34 private:
35  union Storage {
36  MaxAlign align;
37  char mem[sizeof(T)];
38  };
39 
40  static void create_() {
41  instance_ = new (storage_.mem) T();
42  }
43 
44  static uv_once_t once_;
45  static Storage storage_;
46  static T* instance_;
47 };
48 
49 template <class T> uv_once_t Singleton<T>::once_ = UV_ONCE_INIT;
50 template <class T> typename Singleton<T>::Storage Singleton<T>::storage_;
51 template <class T> T* Singleton<T>::instance_;
52 
53 } // namespace core
54 } // namespace roc
55 
56 #endif // ROC_CORE_SINGLETON_H_
Convert errno to string.
A union with maximum possible allignment.
Definition: alignment.h:21
Root namespace.
Alignment.
Singleton.
Definition: singleton.h:26
Base class for non-copyable objects.
Definition: noncopyable.h:23
Panic function.
Non-copyable object.
static T & instance()
Get singleton instance.
Definition: singleton.h:29