Easy Navigation
Loading...
Searching...
No Matches
Singleton.hpp
Go to the documentation of this file.
1// Copyright 2025 Intelligent Robotics Lab
2//
3// This file is part of the project Easy Navigation (EasyNav in short)
4// licensed under the GNU General Public License v3.0.
5// See <http://www.gnu.org/licenses/> for details.
6//
7// Easy Navigation program is free software: you can redistribute it and/or modify
8// it under the terms of the GNU General Public License as published by
9// the Free Software Foundation, either version 3 of the License, or
10// (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU General Public License for more details.
16//
17// You should have received a copy of the GNU General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21#ifndef EASYNAV_COMMON__SINGLETON_H_
22#define EASYNAV_COMMON__SINGLETON_H_
23
24#include <memory>
25#include <mutex>
26#include <utility>
27
28namespace easynav
29{
30
31template<class C>
33{
34public:
35 template<typename ... Args>
36 static C * getInstance(Args &&... args)
37 {
38 std::call_once(init_flag_, [&]() {
39 instance_ = std::make_unique<C>(std::forward<Args>(args)...);
40 });
41 return instance_.get();
42 }
43
44 static void removeInstance()
45 {
46 instance_.reset();
47 init_flag_ = std::once_flag();
48 }
49
50 template<typename ... Args>
51 static C & get(Args &&... args)
52 {
53 getInstance(std::forward<Args>(args)...);
54 return *instance_;
55 }
56
57protected:
58 Singleton() = default;
59 ~Singleton() = default;
60
61 Singleton(const Singleton &) = delete;
62 Singleton & operator=(const Singleton &) = delete;
63
64private:
65 static std::unique_ptr<C> instance_;
66 static std::once_flag init_flag_;
67};
68
69template<class C>
70std::unique_ptr<C> Singleton<C>::instance_ = nullptr;
71
72template<class C>
73std::once_flag Singleton<C>::init_flag_;
74
75#define SINGLETON_DEFINITIONS(ClassName) \
76public: \
77 static ClassName * getInstance() \
78 { \
79 return ::easynav::Singleton<ClassName>::getInstance(); \
80 } \
81 template<typename ... Args> \
82 static ClassName * getInstance(Args && ... args) \
83 { \
84 return ::easynav::Singleton<ClassName>::getInstance( \
85 std::forward<Args>(args)...); \
86 }
87
88} // namespace easynav
89
90#endif // EASYNAV_COMMON__SINGLETON_H_
static C & get(Args &&... args)
Definition Singleton.hpp:51
Singleton(const Singleton &)=delete
static void removeInstance()
Definition Singleton.hpp:44
Singleton & operator=(const Singleton &)=delete
~Singleton()=default
static C * getInstance(Args &&... args)
Definition Singleton.hpp:36
Definition RTTFBuffer.hpp:30