单例模式
删除析构函数通常意味着单例对象应该一直存活直到程序结束。在单例模式中,这通常是可取的,因为单例对象的生命周期通常与应用程序的生命周期相同。但是这样的话需要有一个函数来回收资源。
以下例子:
- 使用双重检查锁实现(线程安全)
- 实现模板来创建单例
#include <iostream>
#include <mutex>
template <typename T>
class Singleton
{
private:
Singleton() = default;
virtual ~Singleton() = default;
static T* instance;
static std::mutex mtx;
public:
template<typename... Args>
static T* Instance(Args&&... args)
{
if(instance == nullptr)
{
std::lock_guard<std::mutex> lock(mtx);
if(instance == nullptr)
{
std::cout << "new" << std::endl;
instance = new T(std::forward<Args>(args)...);
}
}
return instance;
}
static void Destroy()
{
if(instance != nullptr)
{
std::lock_guard<std::mutex> lock(mtx);
if(instance != nullptr)
{
delete instance;
instance = nullptr;
std::cout << "delete" << std::endl;
}
}
}
};
template <typename T>
T* Singleton<T>::instance = nullptr;
template <typename T>
std::mutex Singleton<T>::mtx;
class A
{
public:
A()
{
a = 10;
}
int a;
};
using namespace std;
int main()
{
cout << Singleton<A>::Instance()->a << endl;
Singleton<A>::Instance()->a = 1000;
cout << Singleton<A>::Instance()->a << endl;
Singleton<A>::Destroy();
cout << Singleton<A>::Instance()->a << endl;
//cout << Singleton<A>::Instance()->a << endl;
return 0;
}
以下例子为初始化时就创建
#include <iostream>
#include <mutex>
class A
{
public:
A()
{
a = 10;
}
int a;
};
template <typename T>
class Singleton
{
private:
Singleton() = default;
virtual ~Singleton() = delete;
static T* instance;
public:
static T* Instance()
{
return instance;
}
};
template<typename T>
T* Singleton<T>::instance = new T();
using namespace std;
int main()
{
cout << Singleton<A>::Instance()->a << endl;
Singleton<A>::Instance()->a = 20;
cout << Singleton<A>::Instance()->a << endl;
return 0;
}
标签:std,初始化,Singleton,cout,instance,创建,Instance,单例
From: https://www.cnblogs.com/hy227/p/18186148