在c++中,可以通过以下几种方式来实现单例模式: 饿汉式单例模式(Eager Initialization): 在类定义中静态地创
在c++中,可以通过以下几种方式来实现单例模式:
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if(instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if(instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx; // 互斥锁
Singleton() {}
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() {}
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
这些是常见的几种单例模式的实现方式,选择哪种方式取决于具体的需求和场景。
--结束END--
本文标题: c++单例模式的实现方式有哪些
本文链接: https://www.lsjlt.com/news/570347.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0