M
Manuel
Consider the classic singleton (from Thinking in C++):
-----------------------------------------------------
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;
class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
-----------------------------------------------------
I've read this type of singleton is often used to store the global
variables, but I don't have found a clear explanation.
An example:
if, in file main.cpp, I write
Singleton Singleton::s(47);
Singleton& s = Singleton::instance();
and, in foo1.cpp, I write
Singleton& s1 = Singleton::instance();
and in foo2.cpp I write
Singleton& s2 = Singleton::instance();
these instances (s, s1 and s2) are the same object, so all methods and
properties are shared???? Because Singleton::s is static, I suppose yes,
but I'm not sure...
thx,
Manuel
-----------------------------------------------------
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;
class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
-----------------------------------------------------
I've read this type of singleton is often used to store the global
variables, but I don't have found a clear explanation.
An example:
if, in file main.cpp, I write
Singleton Singleton::s(47);
Singleton& s = Singleton::instance();
and, in foo1.cpp, I write
Singleton& s1 = Singleton::instance();
and in foo2.cpp I write
Singleton& s2 = Singleton::instance();
these instances (s, s1 and s2) are the same object, so all methods and
properties are shared???? Because Singleton::s is static, I suppose yes,
but I'm not sure...
thx,
Manuel