2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <unordered_map>
27 // This internal-use-only class is used to create all leaked Meyers singletons.
28 // It guarantees that only one instance of every such singleton will ever be
29 // created, even when requested from different compilation units linked
31 class StaticSingletonManager {
33 static StaticSingletonManager& instance();
35 template <typename T, typename Tag, typename F>
36 inline T* create(F&& creator) {
37 auto& entry = [&]() mutable -> Entry<T>& {
38 std::lock_guard<std::mutex> lg(mutex_);
40 auto& id = typeid(TypePair<T, Tag>);
41 auto& entryPtr = map_[id];
43 entryPtr = new Entry<T>();
45 assert(dynamic_cast<Entry<T>*>(entryPtr) != nullptr);
46 return *static_cast<Entry<T>*>(entryPtr);
49 std::lock_guard<std::mutex> lg(entry.mutex);
52 entry.ptr = creator();
58 template <typename A, typename B>
61 StaticSingletonManager() {}
68 struct Entry : public EntryIf {
73 std::unordered_map<std::type_index, EntryIf*> map_;
77 template <typename T, typename Tag, typename F>
78 inline T* createGlobal(F&& creator) {
79 return StaticSingletonManager::instance().create<T, Tag>(
80 std::forward<F>(creator));
83 template <typename T, typename Tag>
84 inline T* createGlobal() {
85 return createGlobal<T, Tag>([]() { return new T(); });