单例模式

1.
#include <iostream>
#include <iomanip>

using namespace std;

class singleton{
private:
    singleton(){}
    static singleton *p;
public:
    static singleton *getinstance(){    //唯一外部接口
        if(p == NULL)
            p = new singleton();
        return p;
    }
};

singleton *singleton::p = NULL;

int main(){
    cout << hex << singleton::getinstance() << endl;
    cout << hex << singleton::getinstance() << endl;
    return 0;
}
$ ./a.out
0x9303008
0x9303008

2.
int main(){
    singleton *p = new singleton;
    return 0;
}
error: ‘singleton::singleton()’ is private

3.多线程模式
C++0X以后, 编译器会保证内部静态变量的线程安全性,所以可以不加锁,但是之前的版本需要加锁
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <pthread.h>

using namespace std;

class locker{
private:
    pthread_mutex_t singleton_mutex;
public:
    locker(){
        int res = pthread_mutex_init(&singleton_mutex, NULL);
        if(res){
            perror("mutex initialization failed!");
            exit(-1);
        }
    }
    ~locker(){
        pthread_mutex_destroy(&singleton_mutex);
    }

    void lock(){
        pthread_mutex_lock(&singleton_mutex);
    }

    void unlock(){
        pthread_mutex_unlock(&singleton_mutex);
    }
};

class singleton{
private:
    static singleton *p;
    static locker *plock;
public:
    static singleton *getinstance(){
        plock->lock();
        if(NULL == p)
            p = new singleton();
        return p;
        plock->unlock();
    }
};

singleton *singleton::p = NULL;
locker* singleton::plock = new locker;

4.加锁性能较低,此方法没有判定区域,不需加锁
class Singleton
{
private:
    static const Singleton* m_instance;
    Singleton(){}
public:
    static const Singleton* getInstance()
    {
        return m_instance;
    }
};

const Singleton* Singleton::m_instance = new SingletonStatic;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值