feat: add Singleton Pattern

This commit is contained in:
XMuli 2022-12-24 01:30:52 +08:00
parent ed401eda98
commit 8a876a756e
No known key found for this signature in database
GPG Key ID: 9554B5DD5B8E986A
2 changed files with 23 additions and 1 deletions

View File

@ -1 +1,2 @@
#include "Singleton.h"

View File

@ -6,7 +6,7 @@
******************************************************************/
#pragma once
// 《Effective C++》提出了一种更优雅的单例模式实现,称为 Meyers' Singleton
// 推荐使用 →《Effective C++》提出了一种更优雅的单例模式实现,称为 Meyers' Singleton
class Singleton
{
public:
@ -22,3 +22,24 @@ private:
Singleton& operator=(const Singleton& obj) = delete;
};
//---------------------------------------------------------
// 不推荐使用 → Eager Singleton 是线程安全的,但存在潜在问题 no-local static 对象在不同编译单元中的初始化顺序是未定义的
class Singleton2
{
public:
static Singleton2& instance() {
return instan;
}
private:
Singleton2() {};
~Singleton2() {};
Singleton2(const Singleton2&) = delete;
Singleton2& operator=(const Singleton2&) = delete;
private:
static Singleton2 instan;
};
Singleton2 Singleton2::instan;