Last active
January 14, 2022 01:22
-
-
Save whoo24/11a665684a52e7e1e0ae09a950cbea1a to your computer and use it in GitHub Desktop.
The nested class named FProtection prevents the creation of instances by direct calling the constructor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
template <typename T> | |
class TSingleton { | |
public: | |
TSingleton() {} | |
~TSingleton() { | |
delete(Instance_); | |
} | |
private: | |
static T* Instance_; | |
protected: | |
struct FProtection {}; | |
public: | |
static T& GetInstance() { | |
if (Instance_ == nullptr) { | |
Instance_ = new T(FProtection()); | |
} | |
return *Instance_; | |
} | |
TSingleton(TSingleton const&) = delete; | |
void operator=(TSingleton const&) = delete; | |
}; | |
template <typename T> T* TSingleton<T>::Instance_; | |
class Foo : public TSingleton<Foo> { | |
public: | |
void* GetAddress () { | |
return reinterpret_cast<void*>(this); | |
} | |
Foo (const FProtection&) {} | |
}; | |
int main() { | |
//auto foo = new Foo(Foo::FProtection()); // C2248 compile error | |
std::cout << Foo::GetInstance().GetAddress() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment