Easy Navigation
Loading...
Searching...
No Matches
Singleton.hpp
Go to the documentation of this file.
1// Copyright 2025 Intelligent Robotics Lab
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15
16#ifndef EASYNAV_COMMON__SINGLETON_HPP_
17#define EASYNAV_COMMON__SINGLETON_HPP_
18
19#include <mutex>
20#include <utility>
21
22namespace easynav
23{
24
25template<class C>
27{
28public:
29 template<typename ... Args>
30 static C * getInstance(Args &&... args)
31 {
32 std::lock_guard<std::mutex> lock(mutex_);
33 if (!instance_) {
34 instance_ = new C(std::forward<Args>(args)...);
35 }
36 return instance_;
37 }
38
50 static void removeInstance()
51 {
52 std::lock_guard<std::mutex> lock(mutex_);
53 delete instance_;
54 instance_ = nullptr;
55 }
56
57 template<typename ... Args>
58 static C & get(Args &&... args)
59 {
60 return *getInstance(std::forward<Args>(args)...);
61 }
62
63protected:
64 Singleton() = default;
65 ~Singleton() = default;
66
67 Singleton(const Singleton &) = delete;
68 Singleton & operator=(const Singleton &) = delete;
69
70private:
71 // Never destroyed at exit: the plugin library that built it (its vtable) may be unloaded
72 static C * instance_;
73 static std::mutex mutex_;
74};
75
76template<class C>
77C * Singleton<C>::instance_ = nullptr;
78
79template<class C>
80std::mutex Singleton<C>::mutex_;
81
82#define SINGLETON_DEFINITIONS(ClassName) \
83public: \
84 static ClassName * getInstance() \
85 { \
86 return ::easynav::Singleton<ClassName>::getInstance(); \
87 } \
88 template<typename ... Args> \
89 static ClassName * getInstance(Args && ... args) \
90 { \
91 return ::easynav::Singleton<ClassName>::getInstance( \
92 std::forward<Args>(args)...); \
93 }
94
95} // namespace easynav
96
97#endif // EASYNAV_COMMON__SINGLETON_HPP_
static C & get(Args &&... args)
Definition Singleton.hpp:58
Singleton(const Singleton &)=delete
static void removeInstance()
Destroy the current instance, if any; the next getInstance()/get() call creates a fresh one.
Definition Singleton.hpp:50
Singleton & operator=(const Singleton &)=delete
~Singleton()=default
static C * getInstance(Args &&... args)
Definition Singleton.hpp:30
Definition CircularBuffer.hpp:24