Explain Singleton's Implementation

Nov 16, 2013 at 7:50pm
Could someone help me out by explaining what this code for a Singleton class means? Specifically, I do not understand why the definitions use pointers instead of the static type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/////////////////////
//class declaration//
/////////////////////

class Singleton
{
private:
	Singleton(void);
public:
	~Singleton(void);
	static Singleton *pInstance;
	static Singleton *GetInstance();
	int value;
}


/////////////////////
//class definitions//
/////////////////////

Singleton::Singleton(void)
{
	cout << "Singleton Class with a Static Pointer\n\n";
}

Singleton::~Singleton(void)
{
	//destructor
}

Singleton * Singleton::pInstance = 0;

Singleton * Singleton::GetInstance()
{
	if(Singleton::pInstance == 0) {
		Singleton::pInstance = new Singleton();
	}
	return Singleton::pInstance;
}
Nov 16, 2013 at 8:24pm
I have a better understanding of what this code means now after finding this site which explains what static member functions are:
https://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr039.htm


The only question I have now is why are the static member functions defined using pointers? I currently think it is because the Singleton constructor is a private member instead, but haven't found any research to back that up.
Nov 16, 2013 at 8:47pm
I think I may have found the answer to why the static members are defined with pointers from this source:
http://forums.codeguru.com/showthread.php?344782-C-Design-Pattern-What-is-a-Singleton-class


The only thing that makes it questionable is that it is a forum post from another user. It looks accurate like the user understands Singleton pretty well, so I will go with that.
Topic archived. No new replies allowed.