LazyValue.hpp
Go to the documentation of this file.
1 // @formatter:off
2 //
3 // Balau core C++ library
4 //
5 // Copyright (C) 2008 Bora Software (contact@borasoftware.com)
6 //
7 // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003.
8 // See the LICENSE file for the full license text.
9 //
10 
16 
17 #ifndef COM_BORA_SOFTWARE__BALAU_CONCURRENT__LAZY_VALUE
18 #define COM_BORA_SOFTWARE__BALAU_CONCURRENT__LAZY_VALUE
19 
20 #include <atomic>
21 #include <functional>
22 #include <mutex>
23 
24 namespace Balau::Concurrent {
25 
36 template <typename T> class LazyValue {
42  public: explicit LazyValue(std::function<void (T &)> destruct_ = std::function<void (T &)>())
43  : destruct(destruct_)
44  , constructed(false) {}
45 
49  public: ~LazyValue() {
50  std::lock_guard<std::mutex> lock(mutex);
51 
52  if (constructed && destruct) {
53  destruct(value);
54  }
55  }
56 
62  public: T & operator () (std::function<T ()> construct) {
63  if (!constructed.load(std::memory_order_acquire)) {
64  std::lock_guard<std::mutex> lock(mutex);
65 
66  if (!constructed.load(std::memory_order_relaxed)) {
67  value = construct();
68  constructed.store(true, std::memory_order_release);
69  }
70  }
71 
72  return value;
73  }
74 
86  public: bool isConstructed() const {
87  return constructed;
88  }
89 
97  public: std::mutex & getMutex() {
98  return mutex;
99  }
100 
102 
103  private: std::function<void (T &)> destruct;
104  private: std::atomic_bool constructed;
105  private: std::mutex mutex;
106  private: T value;
107 };
108 
109 } // namespace Balau::Concurrent
110 
111 #endif // COM_BORA_SOFTWARE__BALAU_CONCURRENT__LAZY_VALUE
T & operator()(std::function< T()> construct)
Get the value, constructing it by calling the supplied function if necessary.
Definition: LazyValue.hpp:62
LazyValue(std::function< void(T &)> destruct_=std::function< void(T &)>())
Create a lazy value.
Definition: LazyValue.hpp:42
~LazyValue()
Destroy the lazy value instance.
Definition: LazyValue.hpp:49
Member variable style lazy setting of a value.
Definition: LazyValue.hpp:36
Concurrency control classes.
Definition: CyclicBarrier.hpp:26
bool isConstructed() const
Returns true if the value has been constructed.
Definition: LazyValue.hpp:86
std::mutex & getMutex()
Get the internal mutex in order to synchronise on external code.
Definition: LazyValue.hpp:97