- #include "iostream"
-
- using namespace std;
-
- class AloneClass {
- public:
- static AloneClass* Instance() {
- if (aloneClass == nullptr) {
- aloneClass = new AloneClass();
- }
- return aloneClass;
- }
- void PrintS() {
- cout << 234 << endl;
- }
-
- private:
- AloneClass() {
-
- }
- ~AloneClass();
- AloneClass(const AloneClass& alone);
- AloneClass& operator=(const AloneClass& alone);
-
- private:
- static AloneClass* aloneClass;
- };
-
- AloneClass* AloneClass::aloneClass = nullptr;
-
- int main() {
- AloneClass::Instance()->PrintS();
-
- return 0;
- }
这种情况是不是多线程的情况,多线程若需要单例,则需要调用call_once函数
- #include "iostream"
-
- using namespace std;
-
- template<typename Type>
- class SingleClass
- {
- public:
- static Type* Instance() {
- if (singleClass == nullptr) {
- singleClass = new Type();
- }
- return singleClass;
- }
-
- private:
- SingleClass() {}
- ~SingleClass() {}
- SingleClass(const Type& single) {}
- SingleClass& operator= (const Type& single) {}
- private:
- static Type* singleClass;
- };
-
- template<typename Type>
- Type* SingleClass
::singleClass = nullptr; - class B {
- friend SingleClass<B>;
- public:
- void Print() {
- cout << 1234 << endl;
- }
- private :
- B() {}
- ~B() {}
- B(const B& b) {}
- B& operator=(const B& b) {}
- };
-
- int main() {
- SingleClass<B>::Instance()->Print();
-
- return 0;
- }
修改成为模板形式
UE版本
- // Copyright Epic Games, Inc. All Rights Reserved.
-
- #pragma once
-
- #include "CoreMinimal.h"
- #include "mutex"
-
- template<typename Type>
- class SingleClass
- {
- public:
- static Type* Instance() {
- std::lock_guard<std::mutex> lockGuard(mtx);
- if (singleClass == nullptr) {
- singleClass = NewObject<Type>();
- }
- return singleClass;
- }
-
- private:
- SingleClass() {}
- ~SingleClass() {}
- SingleClass(const Type& single) {}
- SingleClass& operator= (const Type& single) {}
- static std::mutex mtx;
- private:
- static Type* singleClass;
- };
-
- template<typename Type>
- Type* SingleClass
::singleClass = nullptr; - template<typename Type>
- std::mutex SingleClass<Type>::mtx;
这里加了锁,防止多线程造成两次调用Instance实例出两个实例
- // Copyright Epic Games, Inc. All Rights Reserved.
-
- #pragma once
-
- #include "CoreMinimal.h"
- #include "SingleClass.h"
- #include "GameFramework/Actor.h"
- #include "CreateActorFactory.generated.h"
-
- UCLASS()
- class ACreateActorFactory : public AActor
- {
- GENERATED_BODY()
- friend class SingleClass
; - public:
- void Print();
- private:
- ACreateActorFactory() {}
- ~ACreateActorFactory() {}
- };
- // Copyright Epic Games, Inc. All Rights Reserved.
-
- #include "CreateActorFactory.h"
-
- void ACreateActorFactory::Print() {
- GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, "324");
- }
- // Copyright Epic Games, Inc. All Rights Reserved.
-
- #include "ActorBase.h"
- #include "SingleClass.h"
- #include "CreateActorFactory.h"
-
- AActorBase::AActorBase() {
-
- }
-
- void AActorBase::BeginPlay() {
- Super::BeginPlay();
-
- SingleClass
::Instance()->Print(); - }