c++11單例模板類

#ifndef ITC_DAAS_SINGLETON_H_
#define ITC_DAAS_SINGLETON_H_

#include <memory>
#include <mutex>

class Uncopyable {
protected:
    Uncopyable(){};
    ~Uncopyable(){};

private:
    Uncopyable(const Uncopyable& that);
    Uncopyable& operator=(const Uncopyable& that);
};

template <typename T>
class Singleton : public Uncopyable {
public:
    template <typename... ArgTypes>
    static T* getInstance(ArgTypes&&... args) {
        static std::once_flag of;
        std::call_once(
            of, [&]() { Singleton::instance_.reset(new T(std::forward<ArgTypes>(args)...)); });

        return instance_.get();
    }

private:
    static std::unique_ptr<T> instance_;
};

template <class T>
std::unique_ptr<T> Singleton<T>::instance_ = nullptr;


#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章