[Design Pattern] Singlton - 单例

this code copy from muduo.

// noncopyable.h
#pragma once

class noncopyable
{
protected:
    noncopyable() = default;
    ~noncopyable() = default;
private:
    noncopyable( const noncopyable& );
    const noncopyable& operator=( const noncopyable& );
};
// singleton.h
#pragma once

#include <assert.h>
#include <pthread.h>
#include <stdlib.h> // atexit

#include "noncopyable.h"

// This doesn't detect inherited member functions!
// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
template<typename T>
struct has_no_destroy
{
    template <typename C> static char test(decltype(&C::no_destroy));
    template <typename C> static int32_t test(...);
    const static bool value = sizeof(test<T>(0)) == 1;
};

template<typename T>
class singleton : noncopyable
{
public:
    static T& get_instance()
    {
        pthread_once(&ponce_, &singleton::init);
        assert(value_ != NULL);
        return *value_;
    }

private:
    static void init()
    {
        value_ = new T();
        if (!has_no_destroy<T>::value)
        {     
            ::atexit(destroy);
        }     
    }

    static void destroy()
    {
        typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; 
        T_must_be_complete_type dummy; (void) dummy;

        delete value_;
        value_ = NULL;
    }

 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;

发表评论

电子邮件地址不会被公开。必填项已用 * 标注