C++ note 3 - Singleton
Singleton:
- Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
- Can act just like namespace
- A simple implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Singleton
{
private:
Singleton() {} // Disable from instantiating
static Singleton Instance;
public:
static Singleton& Get() {
return s_Instance;
}
void Func();
};
Singleton Singleton::s_Instance;
int main()
{
Singleton::Get().Func();
return 0;
} - Issues from above:
- One can do
Singleton instance = Singleton::Get();instead ofSingleton& instance = Singleton::Get();will copy all data in the Singleton and create an additional Singleton. Should mark the copy constructer, and the assignment operator as delete.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Singleton
{
private:
Singleton() {} // Disable from instantiating
static Singleton Instance;
public:
Singleton(const Singleton&) = delete; // solve the issue
Singleton& operator=(const Singleton&) = delete;
static Singleton& Get() {
return s_Instance;
}
void Func();
};
- One can do
Can remove the global initialization and create inside
Get().1
2
3
4
5
6
7
8
9
10
11
12
13class Singleton
{
private:
Singleton() {} // Disable from instantiating
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton& Get() {
static Singleton s_Instance; // Init from here
return s_Instance;
}
void Func();
};A final version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#include <iostream>
class Singleton
{
private:
Singleton() {} // Disable from instantiating
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton& Get() {
static Singleton s_Instance; // Init from here
return s_Instance;
}
void Func() {
std::cout << "Func called" << std::endl;
};
};
int main()
{
Singleton::Get().Func();
return 0;
}