// Copyright (c) 2022 NetEase, Inc. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. #ifndef BASE_SINGLETON_H_ #define BASE_SINGLETON_H_ #include #include namespace utils { template class Singleton { public: static T* getInstance(); Singleton(const Singleton& other) = delete; Singleton& operator=(const Singleton& other) = delete; private: static std::mutex mutex; static T* instance; }; template std::mutex Singleton::mutex; template T* Singleton::instance; template T* Singleton::getInstance() { if (instance == nullptr) { std::lock_guard locker(mutex); if (instance == nullptr) { instance = new T(); } } return instance; } #define SINGLETONG(Class) \ private: \ friend class utils::Singleton; \ \ public: \ static Class* getInstance() { return utils::Singleton::getInstance(); } #define HIDE_CONSTRUCTOR(Class) \ private: \ Class() = default; \ Class(const Class& other) = delete; \ Class& operator=(const Class& other) = delete; \ } } #endif // BASE_SINGLETON_H_