1class S
2{
3 public:
4 static S& getInstance()
5 {
6 static S instance; // Guaranteed to be destroyed.
7 // Instantiated on first use.
8 return instance;
9 }
10 private:
11 S() {} // Constructor? (the {} brackets) are needed here.
12
13 // C++ 03
14 // ========
15 // Don't forget to declare these two. You want to make sure they
16 // are unacceptable otherwise you may accidentally get copies of
17 // your singleton appearing.
18 S(S const&); // Don't Implement
19 void operator=(S const&); // Don't implement
20
21 // C++ 11
22 // =======
23 // We can use the better technique of deleting the methods
24 // we don't want.
25 public:
26 S(S const&) = delete;
27 void operator=(S const&) = delete;
28
29 // Note: Scott Meyers mentions in his Effective Modern
30 // C++ book, that deleted functions should generally
31 // be public as it results in better error messages
32 // due to the compilers behavior to check accessibility
33 // before deleted status
34};
1#include <iostream>
2
3using namespace std;
4
5class Singleton {
6 static Singleton *instance;
7 int data;
8
9 // Private constructor so that no objects can be created.
10 Singleton() {
11 data = 0;
12 }
13
14 public:
15 static Singleton *getInstance() {
16 if (!instance)
17 instance = new Singleton;
18 return instance;
19 }
20
21 int getData() {
22 return this -> data;
23 }
24
25 void setData(int data) {
26 this -> data = data;
27 }
28};
29
30//Initialize pointer to zero so that it can be initialized in first call to getInstance
31Singleton *Singleton::instance = 0;
32
33int main(){
34 Singleton *s = s->getInstance();
35 cout << s->getData() << endl;
36 s->setData(100);
37 cout << s->getData() << endl;
38 return 0;
39}