Skip to content
This repository was archived by the owner on Apr 16, 2026. It is now read-only.

Commit c0a5b03

Browse files
committed
Add singleton class
1 parent 7fc93c9 commit c0a5b03

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

include/cloysterhpc/functions.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,36 @@
1616
#include <type_traits>
1717

1818
namespace cloyster {
19+
20+
template <typename T>
21+
class Singleton {
22+
// Private constructor to prevent direct instantiation
23+
Singleton() = default;
24+
25+
// Static members for singleton management
26+
static std::unique_ptr<T> instance;
27+
static std::once_flag initFlag;
28+
public:
29+
Singleton(Singleton&&) = delete;
30+
Singleton& operator=(Singleton&&) = delete;
31+
Singleton(const Singleton&) = delete;
32+
Singleton& operator=(const Singleton&) = delete;
33+
~Singleton() = delete;
34+
35+
static void init(std::unique_ptr<T> value) {
36+
std::call_once(initFlag, [&](){
37+
instance = std::move(value);
38+
});
39+
}
40+
41+
static T& get() {
42+
std::call_once(initFlag, []() {
43+
instance = std::make_unique<T>();
44+
});
45+
return *instance;
46+
}
47+
};
48+
1949
// Globals
2050
extern bool dryRun;
2151

src/functions.cpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ using cloyster::services::BaseRunner;
3030
using cloyster::services::DryRunner;
3131
using cloyster::services::Runner;
3232

33+
34+
template <typename T>
35+
std::unique_ptr<T> Singleton<T>::instance = nullptr;
36+
37+
template <typename T>
38+
std::once_flag Singleton<T>::initFlag;
39+
3340
namespace {
3441
std::tuple<bool, std::optional<std::string>> retrieveLine(
3542
boost::process::ipstream& pipe_stream,
@@ -69,14 +76,12 @@ using cloyster::services::repos::RepoManager;
6976
static std::unique_ptr<Cluster> clusterSingleton;
7077
void initClusterSingleton(std::unique_ptr<Cluster> cluster)
7178
{
72-
assert(!clusterSingleton);
73-
clusterSingleton = std::move(cluster);
79+
Singleton<Cluster>::init(std::move(cluster));
7480
}
7581

7682
Cluster& getClusterSingleton()
7783
{
78-
assert(clusterSingleton);
79-
return *clusterSingleton;
84+
return Singleton<Cluster>::get();
8085
}
8186

8287
std::shared_ptr<RepoManager> getRepoManager(const OS& osinfo)

0 commit comments

Comments
 (0)