Design pattern.
A Singleton is a design pattern that ensures a class has only one instance and provides a global point of access to that instance.
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
| #include <iostream>
class Singleton { private: static Singleton* _instance;
Singleton() { std::cout << "Singleton created\n"; }
Singleton(const Singleton& rhs) = delete; Singleton& operator=(const Singleton& rhs) = delete;
public: static Singleton* getInstance() { if (_instance == nullptr) { _instance = new Singleton(); } return _instance; } };
Singleton* Singleton::_instance = nullptr;
int main() { Singleton* a = Singleton::getInstance(); Singleton* b = Singleton::getInstance(); Singleton* c = Singleton::getInstance();
std::cout << "Memory addresses of a, b and c: " << a << ' ' << b << ' ' << c << '\n'; }
|
1 2
| Singleton created Memory addresses of a, b and c: 0x17662b0 0x17662b0 0x17662b0
|