Is this a good Singleton implementation? Is there anything I should be aware of? If so, how can it be improved?
template <class T>
class Singleton
{
public:
static T& getInstance()
{
static T instance;
return instance;
}
protected:
Singleton() {}
~Singleton() {}
private:
Singleton(Singleton const&);
void operator=(Singleton const&);
};
Usage example:
#include <stdio.h>
class A : public Singleton<A> {
public:
A() {
a = 100;
}
int get_a() { return a; }
void set_a(int v) { a = v; }
private:
int a;
};
A& s = A::getInstance();
void free1() {
printf("%d\n", s.get_a());
}
void free2() {
s.set_a(200);
}
void free3() {
printf("--> %d", s.get_a());
}
void main() {
free1();
free2();
free3();
}
Let's consider an alternative to avoid the usage of Singletons, instead having:
class A : public Singleton<A>
let's say it becomes:
class A
and let's say we define a global variable:
A g_s = A();
and then this global variable will be accessed by other files using external
, would that bring some sort of benefit?
external A g_s;