1.特点:全局变量,整个项目只提供一个对象。
2.应用场景:
a: 设备管理器,系统中可能有多个设备,但是只有一个设备管理器,用于管理设备驱动;
b: 数据池,用来缓存数据的数据结构,需要在一处写,多处读取或者多处写,多处读取;
3.实现(未加锁的懒汉模式):
class Singleton
{
public:
~Singleton(){
std::cout<<"destructor called!"<<std::endl;
}
Singleton(const Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Singleton& get_instance(){
static Singleton instance;
return instance;
}
private:
Singleton(){
std::cout<<"constructor called!"<<std::endl;
}
};
int main(int argc, char *argv[])
{
Singleton& instance_1 = Singleton::get_instance();
Singleton& instance_2 = Singleton::get_instance();
return 0;
}