CppPatterns/Singleton/main.cpp

43 lines
903 B
C++
Raw Permalink Normal View History

2024-03-14 08:37:08 +00:00
#include <cstdlib>
2024-03-14 10:04:04 +00:00
#include <iomanip>
2024-03-14 08:37:08 +00:00
#include <iostream>
2024-03-14 10:04:04 +00:00
#include <mutex>
class Singleton {
private:
static Singleton *singleton;
static std::mutex mutex;
Singleton() = default;
public:
Singleton(const Singleton &other) = delete;
Singleton &operator=(const Singleton &) = delete;
static Singleton *GetInstance() {
std::lock_guard<std::mutex> lock(mutex);
if (singleton == nullptr) {
singleton = new Singleton();
}
return singleton;
}
};
Singleton *Singleton::singleton = nullptr;
std::mutex Singleton::mutex;
2024-03-14 08:37:08 +00:00
int main(int argc, char *argv[]) {
std::cout << "Singleton" << std::endl;
2024-03-14 10:04:04 +00:00
auto singleton1 = Singleton::GetInstance();
auto singleton2 = Singleton::GetInstance();
std::cout << std::setw(20) << "Singleton 1: " << singleton1 << std::endl;
std::cout << std::setw(20) << "Singleton 2: " << singleton2 << std::endl;
2024-03-14 08:37:08 +00:00
return EXIT_SUCCESS;
}