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 40 41 42 43 44 45 46 47
| #include <iostream> #include <mutex>
class Singleton { private: static Singleton* instance; static std::mutex mtx;
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public: static Singleton* getInstance() { if (instance == nullptr){ std::lock_guard<std::mutex> lock(mtx); if (instance == nullptr) { instance = new Singleton(); } } return instance; } };
Singleton* Singleton::instance = nullptr; std::mutex Singleton::mtx;
int main() { Singleton* s1 = Singleton::getInstance(); Singleton* s2 = Singleton::getInstance();
if (s1 == s2) { std::cout << "Singleton works, both variables contain the same instance." << std::endl; } else { std::cout << "Singleton failed, variables contain different instances." << std::endl; }
return 0; }
|