In C ++ singleton

Codes are as follows

#include <iostream>
using namespace std;
class Singleon{
private:
    Singleon(){
    cout<<"调用构造函数了"<<endl;
}
    static Singleon* instance;
public:
    static Singleon * getInstance(){
        return instance;
    }
    static Singleon * initInstance(){
        if(instance==nullptr){
            instance=new Singleon();
        }else{
            cout<<"已经创造过对象了,没有再创建"<<endl;
        }
        return instance;
    }
    static void Destory(){
        delete instance;
        instance=nullptr;
    }
};
Singleon *Singleon::instance = nullptr;
int main()
{
    Singleon *s1=Singleon::initInstance();
    Singleon *s2=Singleon::initInstance();
    Singleon *s3=Singleon::initInstance();
    cout<<s1<<endl;
    cout<<s2<<endl;
    cout<<s3<<endl;
}

operation result

调用构造函数了
已经创造过对象了,没有再创建
已经创造过对象了,没有再创建
0x10120e750
0x10120e750
0x10120e750
Program ended with exit code: 0

It should be noted that this is the most low way is better, but also consider the case of multiple threads call the constructor.

Guess you like

Origin www.cnblogs.com/HaoPengZhang/p/11521317.html