C++實現單例


實現代碼如下

#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;
}

運行結果

調用構造函數了
已經創造過對象了,沒有再創建
已經創造過對象了,沒有再創建
0x10120e750
0x10120e750
0x10120e750
Program ended with exit code: 0

值得說明的是,這個是最low的方式,更好的是,還要考慮多線程調用構造函數的事例。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM