Skip to content

Instantly share code, notes, and snippets.

@whoo24
Last active January 14, 2022 01:22
Show Gist options
  • Save whoo24/11a665684a52e7e1e0ae09a950cbea1a to your computer and use it in GitHub Desktop.
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.
#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