xxxxxxxxxx
// NOTE in c++ a singleton is equivalent to just a namespace
class Singleton
{
public:
// Prevents any type of copy or new instance
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
static Singleton& Get()
{
static Singleton instance;
return instance;
}
static int GetData() { return Get().someData}
private:
Singleton() {}
int someData = 1;
};
xxxxxxxxxx
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
xxxxxxxxxx
//Singleton.h
class Singleton
{
private:
static Singleton* instance; // Pointer to the single instance of the class
static std::mutex mutex; // Mutex for thread-safe initialization
Singleton();
public:
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mutex); // Lock for thread safety
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
//Singleton.cpp
#include "Singleton.h"
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
Singleton::Singleton(){};