fw4spl
LazyInstantiator.hpp
1 /* ***** BEGIN LICENSE BLOCK *****
2  * FW4SPL - Copyright (C) IRCAD, 2009-2015.
3  * Distributed under the terms of the GNU Lesser General Public License (LGPL) as
4  * published by the Free Software Foundation.
5  * ****** END LICENSE BLOCK ****** */
6 
7 #ifndef __FWCORE_UTIL_LAZYINSTANTIATOR_HPP__
8 #define __FWCORE_UTIL_LAZYINSTANTIATOR_HPP__
9 
10 #include <boost/thread/once.hpp>
11 #include <boost/noncopyable.hpp>
12 
13 #include "fwCore/macros.hpp"
14 
15 namespace fwCore
16 {
17 namespace util
18 {
19 
21 
27 template< typename INSTANCE_TYPE, typename TAG = LazyInstantiatorDefaultTag >
28 class LazyInstantiator : ::boost::noncopyable
29 {
30 public:
31 
32  typedef INSTANCE_TYPE InstanceType;
33  typedef TAG TagType;
34  typedef std::shared_ptr<InstanceType> InstanceSptrType;
35 
37  static InstanceSptrType getInstance()
38  {
39  static ::boost::once_flag flag = BOOST_ONCE_INIT;
40  ::boost::call_once(&initInstance, flag);
41  return instance();
42  }
43 
44 protected:
45 
47  static void initInstance()
48  {
49  instance();
50  }
51 
53  static InstanceSptrType instance()
54  {
55  static InstanceSptrType s_instance;
56  if(!s_instance)
57  {
58  s_instance = std::make_shared< InstanceType >();
59  }
60  return s_instance;
61  }
62 };
63 
64 } //namespace util
65 } //namespace fwCore
66 
67 #endif /* __FWCORE_UTIL_LAZYINSTANTIATOR_HPP__ */
static InstanceSptrType getInstance()
Returns the singleton instance. This method is thread safe.
This file defines fwCore base macros.
This namespace fwCore provides common foundations for FW4SPL.
Definition: BaseObject.hpp:16
static InstanceSptrType instance()
Initializes once and returns the instance (not thread-safe)
static void initInstance()
Initializes the singleton instance.
A base class for lazy instantiation, constructed on first demand.