Singleton Class

I have some question about singleton class.

1) what is singleton class

2) how can a write a signleton class code

3) can we write any class which return only type of object( i.e. it will contain only same object or assign object) if we create any number of object.
ya i got your message I should do googling before posting any question in this forum :)

But I could not get any help about 3 question from the Google.



The answer to 3 is yes. The singleton pattern can be implemented as a template class, and so can be use by any class.
code snap will be much helpful for me
Give it a go. Try to write a single class for a string and another for another object, then try to generalise it with a template.
http://www.codeproject.com/kb/cpp/singletonrvs.aspx

got link which reply me lot of question
Hi,

But the problem with the code in the given link is that its destructor is never called. So if you do some important stuff in the destructor then it will never get executed. So another method to do this is, return a reference of a static object from the getInstance() method without any check for initialization. Since its a static object it will exist in the memory till the end of the program and once the program exits, this static object will be destroyed.

The principle behind this method is function static objects are constructed only once. So next time when you call getInstance() reference to the already constructed instance is returned.


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
#include "stdafx.h"
#include <iostream>
using namespace std;

class Singleton
{
private:
    Singleton()
    {
        //private constructor
		cout<<"Constructor."<<endl;
    }
public:
    static Singleton& getInstance();
    void method();
    ~Singleton()
    {
		cout<<"Destructor"<<endl;
    }
};

Singleton& Singleton::getInstance()
{
	static Singleton s;
	return s;
}

void Singleton::method()
{
    cout << "Method of the singleton class" << endl;
}

int main()
{
    Singleton::getInstance().method();
    Singleton::getInstance().method();

    return 0;
}


It's not so simple to create a template for a Singleton class. If it were, boost would've provided
one a long time ago.
Topic archived. No new replies allowed.