reference

This documentation is automatically generated from the openFrameworks source code using doxygen and refers to the most recent release, version 0.12.0.

ofSingleton.hpp
Go to the documentation of this file.
1#ifndef OF_SINGLETON_HPP_
2#define OF_SINGLETON_HPP_
3
4// atomic C++17 DCLP CRTP singleton adapted by burton@artificiel.org from
5// https://github.com/jimmy-park/singleton/blob/main/include/singleton_dclp.hpp (1d26f91)
6
7#include <cassert>
8#include <mutex>
9#include <atomic>
10
11namespace of::utils
12{
13
14template <typename Derived>
15class Singleton {
16public:
17 template <typename... Args>
18 static void construct(Args&&... args) {
19 struct Dummy : public Derived {
20 using Derived::Derived;
21 void prohibit_construct_from_derived() const override { }
22 };
23
24 if (!instance_.load(std::memory_order_acquire)) {
25 if (std::lock_guard lock { mutex_ }; !instance_.load(std::memory_order_relaxed)) {
26 instance_.store(new Dummy { std::forward<Args>(args)... }, std::memory_order_release);
27 }
28 }
29 }
30
31 static Derived * instance() {
32 auto * the_instance = instance_.load(std::memory_order_acquire);
33 assert(the_instance);
34 return the_instance;
35 }
36
37 static void destruct() {
38 if (auto * the_instance = instance_.exchange(nullptr, std::memory_order_acq_rel)) {
39 delete the_instance;
40 }
41 }
42
43protected:
44 Singleton() = default;
45 Singleton(const Singleton&) = delete;
46 Singleton(Singleton&&) noexcept = delete;
47 Singleton& operator=(const Singleton&) = delete;
48 Singleton& operator=(Singleton&&) noexcept = delete;
49 virtual ~Singleton() = default;
50
51private:
52 virtual void prohibit_construct_from_derived() const = 0;
53 inline static std::atomic<Derived*> instance_ { nullptr };
54 inline static std::mutex mutex_;
55};
56
57} // end namespace of::utils
58#endif // OF_SINGLETON_HPP_
Definition ofSingleton.hpp:15
static Derived * instance()
Definition ofSingleton.hpp:31
Singleton(const Singleton &)=delete
static void destruct()
Definition ofSingleton.hpp:37
Singleton(Singleton &&) noexcept=delete
static void construct(Args &&... args)
Definition ofSingleton.hpp:18
Definition ofSingleton.hpp:12
Definition ofPixels.h:1522