Files
CPP_Core/psc_global_include/Singleton.hpp
T
2026-06-16 10:56:40 +08:00

37 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include <mutex>
#include <atomic>
namespace Psc {
template<typename Derived>
class Singleton {
public:
static Derived *instance() {
Derived *temp = instance_.load(std::memory_order_acquire);
if (temp == nullptr) {
std::lock_guard<std::mutex> lock(mutex_);
temp = instance_.load(std::memory_order_relaxed);
if (temp == nullptr) {
temp = new Derived;
instance_.store(temp, std::memory_order_release);
}
}
return temp;
}
static void destroy() {
Derived* temp = instance_.exchange(nullptr, std::memory_order_acq_rel);
delete temp; // 若为 nullptrdelete 安全
}
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
protected:
Singleton() = default;
~Singleton() = default;
private:
static std::atomic<Derived *> instance_;
static std::mutex mutex_;
};
template<typename Derived>
std::atomic<Derived *> Singleton<Derived>::instance_(nullptr);
template<typename Derived>
std::mutex Singleton<Derived>::mutex_;
}