summaryrefslogtreecommitdiffstats
path: root/lib/base/lazy-init.hpp
blob: c1da2cd9375f00ceb8ea80fc43f4c8d762b89c71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#ifndef LAZY_INIT
#define LAZY_INIT

#include <atomic>
#include <functional>
#include <mutex>
#include <utility>

namespace icinga
{

/**
 * Lazy object initialization abstraction inspired from
 * <https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?view=netframework-4.7.2>.
 *
 * @ingroup base
 */
template<class T>
class LazyInit
{
public:
	inline
	LazyInit(std::function<T()> initializer = []() { return T(); }) : m_Initializer(std::move(initializer))
	{
		m_Underlying.store(nullptr, std::memory_order_release);
	}

	LazyInit(const LazyInit&) = delete;
	LazyInit(LazyInit&&) = delete;
	LazyInit& operator=(const LazyInit&) = delete;
	LazyInit& operator=(LazyInit&&) = delete;

	inline
	~LazyInit()
	{
		auto ptr (m_Underlying.load(std::memory_order_acquire));

		if (ptr != nullptr) {
			delete ptr;
		}
	}

	inline
	T& Get()
	{
		auto ptr (m_Underlying.load(std::memory_order_acquire));

		if (ptr == nullptr) {
			std::unique_lock<std::mutex> lock (m_Mutex);

			ptr = m_Underlying.load(std::memory_order_acquire);

			if (ptr == nullptr) {
				ptr = new T(m_Initializer());
				m_Underlying.store(ptr, std::memory_order_release);
			}
		}

		return *ptr;
	}

private:
	std::function<T()> m_Initializer;
	std::mutex m_Mutex;
	std::atomic<T*> m_Underlying;
};

}

#endif /* LAZY_INIT */