I was looking across some code and I found an unusual technique to implement public singletons. I have never seen this code style before in any code.
Here's an example of generic singleton code:
Code:
class Test {
private:
Test() {}
Test(const Test&);
Test& operator=(const Test&);
public:
char mem[0xFFF];
static Test& Instance() {
static Test instance;
return instance;
}
void DoStuff(int i) {
mem[i] = i*2;
}
};
and to access:
Code:
Test::Instance().DoStuff(5);
Test::Instance().mem[2] = 10;
And here's an example that does the same thing, just with namespaces.
Code:
namespace Test {
char mem[0xFFF];
void DoStuff(int i) {
mem[i] = i*2;
}
}
Code:
Test::DoStuff(5);
Test::mem[2] = 10;
I was wondering, what are the benefits and drawbacks of either technique? Why would someone choose to implement a singleton class if they want all attributes public? Is there a performance gain by using one of the techniques? And, what are your thoughts on using namespaces like this?
Thanks,
eros.