#ifndef ITC_DAAS_SINGLETON_H_
#define ITC_DAAS_SINGLETON_H_
#include <memory>
#include <mutex>
template <typename T>
class Singleton {
public:
template <typename... ArgTypes>
static T* GetInstance(ArgTypes&&... args) {
std::call_once(
_of,
[](ArgTypes&&... args) {
_instance.reset(new T(std::forward<ArgTypes>(args)...));
},
std::forward<ArgTypes>(args)...
);
return _instance.get();
}
static void destory() {
if (_instance) {
_instance.reset();
}
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static std::once_flag _of;
static std::unique_ptr<T> _instance;
};
template <class T>
std::once_flag Singleton<T>::_of;
template <class T>
std::unique_ptr<T> Singleton<T>::_instance = nullptr;
#endif
#include <iostream>
#include <thread>
#include <chrono>
#include "Singleton.hpp"
class A
{
private:
int _idx;
public:
A(){
std::cout << "def construct class A" << std::endl;
}
A(int idx):_idx(idx) {
std::cout << "construct class A" << std::endl;
}
~A() {
std::cout << "destory class A" << std::endl;
}
void run() {
std::cout << "run: " << _idx << std::endl;
}
};
int main(int argc, char const *argv[])
{
Singleton<A>::GetInstance(1)->run();
Singleton<A>::GetInstance()->run();
Singleton<A>::GetInstance()->run();
Singleton<A>::GetInstance()->run();
Singleton<A>::destory();
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}