ESP-IDF:懒汉式和饿汉式单例模式测试代码
/单例模式测试/
/懒汉式/
class singleton_lazy
{
private:
singleton_lazy(){};
public:
static singleton_lazy *getinstance(){
if (pSingleton == NULL){
pSingleton = new singleton_lazy;
}
return pSingleton;
}
private:
static singleton_lazy *pSingleton;
};
singleton_lazy *singleton_lazy::pSingleton = NULL;
/饿汉式/
class singleton_hungry
{
private:
singleton_hungry(){
cout<<“singleton_hungry构造函数被调用”<<endl;
};
public:
static singleton_hungry *getinstance(){
return pSingleton_hungry;
};
private:
static singleton_hungry *pSingleton_hungry;
};
singleton_hungry *singleton_hungry::pSingleton_hungry = new singleton_hungry();
void test12()
{
cout << “------单例模式测试------” << endl;
singleton_lazy *p1 = singleton_lazy::getinstance();
singleton_lazy *p2 = singleton_lazy::getinstance();
if (p1 == p2)
{
cout << “singleton_lazy p1 == p2” << endl;
}
singleton_hungry *p3 = singleton_hungry::getinstance();
singleton_hungry *p4 = singleton_hungry::getinstance();
if (p3 == p4)
{
cout << "singleton_hungry p3 == p4" << endl;
}
}
extern “C” void app_main(void)
{
test12();
}
结果:
饿汉式构造函数在程序加载阶段被调用:
饿汉式和懒汉式的对象指针都分别指向同一个对象: