proxygen
StaticSingletonManager.h
Go to the documentation of this file.
1 /*
2  * Copyright 2016-present Facebook, Inc.
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 #pragma once
18 
19 #include <typeinfo>
20 
21 #include <folly/CPortability.h>
22 
23 namespace folly {
24 namespace detail {
25 
26 // This internal-use-only class is used to create all leaked Meyers singletons.
27 // It guarantees that only one instance of every such singleton will ever be
28 // created, even when requested from different compilation units linked
29 // dynamically.
31  public:
32  template <typename T, typename Tag, typename F>
34  F&& creator) {
35  return static_cast<T*>(create_<T, Tag>(creator));
36  }
37 
38  private:
39  template <typename A, typename B>
40  struct TypePair {};
41 
42  using Key = std::type_info;
43  using Make = void*(void*);
44 
45  template <typename F>
46  struct Creator {
47  static void* create(void* f) {
48  return static_cast<void*>((*static_cast<F*>(f))());
49  }
50  };
51 
52  template <typename T, typename Tag, typename F>
54  F& creator) {
55  auto const& key = typeid(TypePair<T, Tag>);
56  return create_(key, &Creator<F>::create, &creator);
57  }
58 
59  template <typename T, typename Tag, typename F>
61  F const& creator) {
62  auto const& key = typeid(TypePair<T, Tag>);
63  return create_(key, &Creator<F const>::create, const_cast<F*>(&creator));
64  }
65 
66  FOLLY_NOINLINE static void* create_(Key const& key, Make* make, void* ctx);
67 };
68 
69 template <typename T, typename Tag, typename F>
71  return StaticSingletonManager::create<T, Tag>(static_cast<F&&>(creator));
72 }
73 
74 template <typename T, typename Tag>
76  return StaticSingletonManager::create<T, Tag>([]() { return new T(); });
77 }
78 
79 } // namespace detail
80 } // namespace folly
auto f
#define FOLLY_ALWAYS_INLINE
Definition: CPortability.h:151
folly::std T
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
#define FOLLY_NOINLINE
Definition: CPortability.h:142
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN T * createGlobal(F &&creator)
FOLLY_ALWAYS_INLINE static FOLLY_ATTR_VISIBILITY_HIDDEN void * create_(F const &creator)
FOLLY_ALWAYS_INLINE static FOLLY_ATTR_VISIBILITY_HIDDEN void * create_(F &creator)
#define FOLLY_ATTR_VISIBILITY_HIDDEN
Definition: CPortability.h:160
FOLLY_ALWAYS_INLINE static FOLLY_ATTR_VISIBILITY_HIDDEN T * create(F &&creator)