c++ 单例模式

线程安全

#include <iostream>
#include <process.h>
#include <windows.h>
using namespace std;

class Singelton {
private:

    static Singelton *single;
public:
    static Singelton *GetSingelton();

    void print_addr() {
        printf("%d\n", single);
    }
    ~Singelton()
    {
        printf("deconstructor singleton\n");
    }
};

Singelton *Singelton::single = new Singelton;

Singelton *Singelton::GetSingelton() {
    return single;
}


int main() {

    Singelton *test = Singelton::GetSingelton();
    test->print_addr();
    Singelton *test1 = Singelton::GetSingelton();
    test1->print_addr();

    system("pause");
    return 0;
}

非线程安全

#include <iostream>
#include <process.h>
#include <windows.h>
using namespace std;

class Singelton {
private:
    static Singelton *single;
public:
    static Singelton *GetSingelton();

    void print_addr() {
        printf("%d\n", single);
    }
    ~Singelton()
    {
        printf("deconstructor singleton\n");
    }
};

Singelton *Singelton::single = nullptr;

Singelton *Singelton::GetSingelton() {
    if (single == nullptr) {
        single = new Singelton;
    }
    return single;
}


int main() {
    
    Singelton *test = Singelton::GetSingelton();
    test->print_addr();
    Singelton *test1 = Singelton::GetSingelton();
    test1->print_addr();

    system("pause");
    return 0;
}

 

posted @ 2020-07-21 16:51  r1-12king  阅读(116)  评论(0编辑  收藏  举报