C++ 单例模式

实现方式一:
#include <pthread.h>

template<typename T>
class Singleton : boost::noncopyable {
public:
    static T& instance() {
        pthread_once(&ponce_, &Singleton::init);
        return *value_;
    }
    
    static void init() {
        value_ = new T();
    }
private:
    static pthread_once_t ponce_;
    static T* value_;
};

template<typename T>
pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;

template<typename T>
T* Singleton<T>::value_ = NULL;
 
实现方式二:

#ifndef LOCKER_H_

#define LOCKER_H_

#include "pthread.h"

class locker

{

public:

    inline locker(){        pthread_mutex_init(&mutex,NULL);}

    inline ~locker(){       pthread_mutex_destroy(&mutex);}

    inline void lock(){     pthread_mutex_lock(&mutex);}

    inline void unlock(){   pthread_mutex_unlock(&mutex);}

private:

    pthread_mutex_t mutex;

};

#endif /* LOCKER_H_ */

#ifndef __SINGLETON_H__

#define __SINGLETON_H__

template <typename T>

class Singleton

{

public:

inline static T* getInstance();

inline static void release();

private:

static T* t;

static locker llocker;

};

template <typename T>

inline T* Singleton<T>::getInstance()

{

llocker.lock();

if (!t)

{

t = new T;

}

llocker.unlock();

return t;

}

template<typename T>

inline void Singleton<T>::release()

{

llocker.lock();

if (t)

{

delete t;

t = 0;

}

llocker.unlock();

}

template <typename T> 

T* Singleton<T>::t = 0;

locker Singleton<T>::llocker

#endif // __SINGLE_H__

 

你可能感兴趣的:(C++,null,delete)