I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this.
Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I read there were some changes to that in particular with C++11)? In addition I am not sure at all about the way I am accessing the class within MyFunction()
.
Is it really necessary to use a raw pointer there? Does this code contain any memory leaks?
#include <iostream>
class Singleton
{
private:
Singleton();
~Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
void Test();
};
void Singleton::Test()
{
std::cout << "Test() called" << std::endl;
}
Singleton::Singleton()
{
std::cout << "CONSTRUCTOR CALLED" << std::endl;
}
Singleton::~Singleton()
{
std::cout << "DESTRUCTOR CALLED" << std::endl;
}
void MyFunction()
{
// use the singleton class
Singleton * MySingleton = &Singleton::instance();
MySingleton->Test();
}
int main()
{
MyFunction();
return 0;
}
=
so that you won't accidentally copy the object. \$\endgroup\$