饿汉模式
类实例化就会占用内存,浪费资源,效率高,不存在线程安全问题。
class Singleton{
Singleton() { }
static Singleton* m_instance_ptr;
public:
static Singleton* get_instance() {
return m_instance_ptr;
}
};
Singleton* Singleton::m_instance_ptr = new Singleton();
int main(){
Singleton* instance1 = Singleton::get_instance();
Singleton* instance2 = Singleton::get_instance();
return 0;
}
懒汉模式
延迟加载,节省资源,效率低,存在线程安全问题。
class Singleton {
Singleton() { }
static Singleton* m_instance_ptr;
public:
static Singleton* get_instance() {
if(m_instance_ptr == nullptr)
m_instance_ptr = new Singleton();
return m_instance_ptr;
}
};
Singleton* Singleton::m_instance_ptr = nullptr;
int main(){
Singleton* instance1 = Singleton::get_instance();
Singleton* instance2 = Singleton::get_instance();
return 0;
}
锁 + 智能指针
线程安全(锁)+ 内存回收(智能指针)
#include <iostream>
#include <memory>
#include <mutex>
class Singleton {
public:
typedef std::shared_ptr<Singleton> Ptr;
static Ptr get_instance() {
if(m_instance_ptr == nullptr) {
std::lock_guard<std::mutex> lk(m_mutex);
if(m_instance_ptr == nullptr)
m_instance_ptr = std::shared_ptr<Singleton>(new Singleton);
}
return m_instance_ptr;
}
private:
Singleton() {}
static Ptr m_instance_ptr;
static std::mutex m_mutex;
};
Singleton::Ptr Singleton::m_instance_ptr = nullptr;
std::mutex Singleton::m_mutex;
int main(){
Singleton::Ptr instance1 = Singleton::get_instance();
Singleton::Ptr instance2 = Singleton::get_instance();
return 0;
}
局部静态变量
class Singleton {
public:
Singleton(const Singleton&)=delete;
static Singleton& get_instance() {
static Singleton instance;
return instance;
}
private:
Singleton() {}
};
int main() {
Singleton& instance1 = Singleton::get_instance();
Singleton& instance2 = Singleton::get_instance();
return 0;
}
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!