به این نوع کلاس سینگلتون (Singleton) اطلاق میشه.
یک متغیر static توی کلاس تعریف کنید و پس از اولین نمونه که ساخته میشه بهش مقدار بده دفعه بعد اگر اون متغیر استاتیک مقدار داشته باشه دیگه construcotr کار نکنه.
#include <iostream>
class Singleton
{
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
private:
Singleton() { }
void operator=(const Singleton& other){}
Singleton(const Singleton& other){}//copy constructor
};
int main()
{
Singleton& s1 = Singleton::getInstance();
Singleton& s2 = Singleton::getInstance();
std::cout << &s1 << '\n';
std::cout << &s2 << '\n';
}