Thrill  0.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
singleton.hpp
Go to the documentation of this file.
1 /***************************************************************************
2  * foxxll/singleton.hpp
3  *
4  * Part of FOXXLL. See http://foxxll.org
5  *
6  * Copyright (C) 2008, 2011 Andreas Beckmann <[email protected]>
7  *
8  * Distributed under the Boost Software License, Version 1.0.
9  * (See accompanying file LICENSE_1_0.txt or copy at
10  * http://www.boost.org/LICENSE_1_0.txt)
11  **************************************************************************/
12 
13 #ifndef FOXXLL_SINGLETON_HEADER
14 #define FOXXLL_SINGLETON_HEADER
15 
16 #include <cstdlib>
17 #include <mutex>
18 
20 #include <foxxll/common/types.hpp>
21 
22 namespace foxxll {
23 
24 template <typename INSTANCE, bool destroy_on_exit = true>
25 class singleton
26 {
27  using instance_type = INSTANCE;
30 
32 
34  static void destroy_instance();
35 
36 public:
37  singleton() = default;
38 
39  //! non-copyable: delete copy-constructor
40  singleton(const singleton&) = delete;
41  //! non-copyable: delete assignment operator
42  singleton& operator = (const singleton&) = delete;
43 
45  {
46  if (!instance)
47  return create_instance();
48 
49  return instance;
50  }
51 
52  inline static instance_type & get_ref()
53  {
54  if (!instance)
56 
57  return *instance;
58  }
59 };
60 
61 template <typename INSTANCE, bool destroy_on_exit>
62 typename singleton<INSTANCE, destroy_on_exit>::instance_pointer
64 {
65  static std::mutex create_mutex;
66  std::unique_lock<std::mutex> instance_write_lock(create_mutex);
67  if (!instance) {
68  instance = new instance_type();
69  if (destroy_on_exit)
70  register_exit_handler(destroy_instance);
71  }
72  return instance;
73 }
74 
75 template <typename INSTANCE, bool destroy_on_exit>
77 {
78  instance_pointer inst = instance;
79  instance = reinterpret_cast<instance_pointer>(size_t(-1)); // bomb if used again
80  delete inst;
81 }
82 
83 template <typename INSTANCE, bool destroy_on_exit>
86 
87 } // namespace foxxll
88 
89 #endif // !FOXXLL_SINGLETON_HEADER
90 
91 /**************************************************************************/
static instance_pointer create_instance()
Definition: singleton.hpp:63
static volatile_instance_pointer instance
Definition: singleton.hpp:31
singleton()=default
static void destroy_instance()
Definition: singleton.hpp:76
volatile instance_pointer volatile_instance_pointer
Definition: singleton.hpp:29
instance_type * instance_pointer
Definition: singleton.hpp:28
static instance_pointer get_instance()
Definition: singleton.hpp:44
singleton & operator=(const singleton &)=delete
non-copyable: delete assignment operator
INSTANCE instance_type
Definition: singleton.hpp:27
static instance_type & get_ref()
Definition: singleton.hpp:52
int register_exit_handler(void(*function)(void))
Definition: exithandler.cpp:35