1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifndef CHRE_UTIL_SINGLETON_IMPL_H_ 18#define CHRE_UTIL_SINGLETON_IMPL_H_ 19 20#include <utility> 21 22#include "chre/util/singleton.h" 23 24namespace chre { 25 26template<typename ObjectType> 27typename std::aligned_storage<sizeof(ObjectType), alignof(ObjectType)>::type 28 Singleton<ObjectType>::sObject; 29 30template<typename ObjectType> 31bool Singleton<ObjectType>::sIsInitialized = false; 32 33template<typename ObjectType> 34template<typename... Args> 35void Singleton<ObjectType>::init(Args&&... args) { 36 if (!sIsInitialized) { 37 sIsInitialized = true; 38 new (get()) ObjectType(std::forward<Args>(args)...); 39 } 40} 41 42template<typename ObjectType> 43void Singleton<ObjectType>::deinit() { 44 if (sIsInitialized) { 45 get()->~ObjectType(); 46 sIsInitialized = false; 47 } 48} 49 50template<typename ObjectType> 51bool Singleton<ObjectType>::isInitialized() { 52 return sIsInitialized; 53} 54 55template<typename ObjectType> 56ObjectType *Singleton<ObjectType>::get() { 57 if (sIsInitialized) { 58 return reinterpret_cast<ObjectType *>(&sObject); 59 } else { 60 return nullptr; 61 } 62} 63 64} // namespace chre 65 66#endif // CHRE_UTIL_SINGLETON_IMPL_H_ 67