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 <new> 21#include <utility> 22 23#include "chre/util/singleton.h" 24 25namespace chre { 26 27template<typename ObjectType> 28typename std::aligned_storage<sizeof(ObjectType), alignof(ObjectType)>::type 29 Singleton<ObjectType>::sObject; 30 31template<typename ObjectType> 32bool Singleton<ObjectType>::sIsInitialized = false; 33 34template<typename ObjectType> 35template<typename... Args> 36void Singleton<ObjectType>::init(Args&&... args) { 37 if (!sIsInitialized) { 38 sIsInitialized = true; 39 new (get()) ObjectType(std::forward<Args>(args)...); 40 } 41} 42 43template<typename ObjectType> 44void Singleton<ObjectType>::deinit() { 45 if (sIsInitialized) { 46 get()->~ObjectType(); 47 sIsInitialized = false; 48 } 49} 50 51template<typename ObjectType> 52bool Singleton<ObjectType>::isInitialized() { 53 return sIsInitialized; 54} 55 56template<typename ObjectType> 57ObjectType *Singleton<ObjectType>::get() { 58 return reinterpret_cast<ObjectType *>(&sObject); 59} 60 61template<typename ObjectType> 62ObjectType *Singleton<ObjectType>::safeGet() { 63 if (sIsInitialized) { 64 return reinterpret_cast<ObjectType *>(&sObject); 65 } else { 66 return nullptr; 67 } 68} 69 70} // namespace chre 71 72#endif // CHRE_UTIL_SINGLETON_IMPL_H_ 73