在C++中,单例模式可以通过以下几种方式进行优化:
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = 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;
class Singleton {
private:
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
class Singleton {
private:
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
以上是对C++单例模式进行优化的几种方式,具体选择哪种方式,取决于具体的需求和使用场景。