Movatterモバイル変換


[0]ホーム

URL:


Google Git
Sign in
chromium /chromium /src /refs/heads/main /. /base /lazy_instance.h
blob: 865bb4fbdcc71909eacef05861cf4d19ed50e255 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:06[diff] [blame]1// Copyright 2012 The Chromium Authors
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
Daniel Cheng73999fe62018-01-19 00:28:15[diff] [blame]4//
5// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEPRECATED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
6// Please don't introduce new instances of LazyInstance<T>. Use a function-local
7// static of type base::NoDestructor<T> instead:
8//
9// Factory& Factory::GetInstance() {
10// static base::NoDestructor<Factory> instance;
11// return *instance;
12// }
13// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
14//
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]15// The LazyInstance<Type, Traits> class manages a single instance of Type,
16// which will be lazily created on the first time it's accessed. This class is
17// useful for places you would normally use a function-level static, but you
18// need to have guaranteed thread-safety. The Type constructor will only ever
19// be called once, even if two threads are racing to create the object. Get()
20// and Pointer() will always return the same, completely initialized instance.
21// When the instance is constructed it is registered with AtExitManager. The
22// destructor will be called on program exit.
23//
24// LazyInstance is completely thread safe, assuming that you create it safely.
25// The class was designed to be POD initialized, so it shouldn't require a
26// static constructor. It really only makes sense to declare a LazyInstance as
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]27// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]28//
29// LazyInstance is similar to Singleton, except it does not have the singleton
30// property. You can have multiple LazyInstance's of the same type, and each
31// will manage a unique instance. It also preallocates the space for Type, as
32// to avoid allocating the Type instance on the heap. This may help with the
33// performance of creating the instance, and reducing heap fragmentation. This
34// requires that Type be a complete type so we can determine the size.
35//
36// Example usage:
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]37// static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER;
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]38// void SomeMethod() {
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]39// inst.Get().SomeMethod(); // MyClass::SomeMethod()
maruel@chromium.org52a261f2009-03-03 15:01:12[diff] [blame]40//
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]41// MyClass* ptr = inst.Pointer();
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]42// ptr->DoDoDo(); // MyClass::DoDoDo
43// }
44
45#ifndef BASE_LAZY_INSTANCE_H_
46#define BASE_LAZY_INSTANCE_H_
47
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]48#include<atomic>
willchan@chromium.org359d2bf2010-11-19 20:34:18[diff] [blame]49#include<new>// For placement new.
50
Hans Wennborg7b533712020-06-22 20:52:27[diff] [blame]51#include"base/check_op.h"
David Sandersfc1f17fa2022-04-15 00:15:49[diff] [blame]52#include"base/dcheck_is_on.h"
earthdok@google.comb2206da52013-06-07 22:09:32[diff] [blame]53#include"base/debug/leak_annotations.h"
Gabriel Charettef297f012018-01-17 20:59:07[diff] [blame]54#include"base/lazy_instance_helpers.h"
brettw@chromium.org34b99632011-01-01 01:01:06[diff] [blame]55#include"base/threading/thread_restrictions.h"
Gabriel Charetted90bcc92021-09-21 00:23:10[diff] [blame]56#include"build/build_config.h"
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]57
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]58// LazyInstance uses its own struct initializer-list style static
59// initialization, which does not require a constructor.
Peter Kasting134ef9af2024-12-28 02:30:09[diff] [blame]60#define LAZY_INSTANCE_INITIALIZER \
61{}
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]62
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]63namespacebase{
64
65template<typenameType>
scottmg5e65e3a2017-03-08 08:48:46[diff] [blame]66structLazyInstanceTraitsBase{
craig.schlenter@chromium.orgc1aeaac2010-03-12 15:28:48[diff] [blame]67staticType*New(void* instance){
brettw16289b3e2017-06-13 21:58:40[diff] [blame]68 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance)&(alignof(Type)-1),0u);
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]69// Use placement new to initialize our instance in our preallocated space.
70// The parenthesis is very important here to force POD type initialization.
craig.schlenter@chromium.orgc1aeaac2010-03-12 15:28:48[diff] [blame]71returnnew(instance)Type();
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]72}
scottmg5e65e3a2017-03-08 08:48:46[diff] [blame]73
74staticvoidCallDestructor(Type* instance){
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]75// Explicitly call the destructor.
joth@chromium.org113eee02011-10-25 19:04:48[diff] [blame]76 instance->~Type();
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]77}
78};
79
fischman@chromium.org67f92bc32012-01-26 01:56:19[diff] [blame]80// We pull out some of the functionality into non-templated functions, so we
81// can implement the more complicated pieces out of line in the .cc file.
82namespaceinternal{
83
Joe Downing0d4683d2018-01-24 01:32:38[diff] [blame]84// This traits class causes destruction the contained Type at process exit via
85// AtExitManager. This is probably generally not what you want. Instead, prefer
86// Leaky below.
87template<typenameType>
88structDestructorAtExitLazyInstanceTraits{
89staticconstbool kRegisterOnExit=true;
90#if DCHECK_IS_ON()
91staticconstbool kAllowedToAccessOnNonjoinableThread=false;
92#endif
93
94staticType*New(void* instance){
95returnLazyInstanceTraitsBase<Type>::New(instance);
96}
97
98staticvoidDelete(Type* instance){
99LazyInstanceTraitsBase<Type>::CallDestructor(instance);
100}
101};
102
fischman@chromium.org9fc44162012-01-23 22:56:41[diff] [blame]103// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
104// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
105// instead of:
fischman@chromium.org67f92bc32012-01-26 01:56:19[diff] [blame]106// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
107// my_leaky_lazy_instance;
fischman@chromium.org9fc44162012-01-23 22:56:41[diff] [blame]108// (especially when T is MyLongTypeNameImplClientHolderFactory).
fischman@chromium.org67f92bc32012-01-26 01:56:19[diff] [blame]109// Only use this internal::-qualified verbose form to extend this traits class
110// (depending on its implementation details).
evan@chromium.orgdcc69332010-10-21 20:41:47[diff] [blame]111template<typenameType>
112structLeakyLazyInstanceTraits{
joth@chromium.org113eee02011-10-25 19:04:48[diff] [blame]113staticconstbool kRegisterOnExit=false;
gab190f7542016-08-01 20:03:41[diff] [blame]114#if DCHECK_IS_ON()
willchan@chromium.org359d2bf2010-11-19 20:34:18[diff] [blame]115staticconstbool kAllowedToAccessOnNonjoinableThread=true;
thakis@chromium.org5a8a8062014-03-06 01:11:54[diff] [blame]116#endif
willchan@chromium.org359d2bf2010-11-19 20:34:18[diff] [blame]117
evan@chromium.orgdcc69332010-10-21 20:41:47[diff] [blame]118staticType*New(void* instance){
earthdok@google.comb2206da52013-06-07 22:09:32[diff] [blame]119 ANNOTATE_SCOPED_MEMORY_LEAK;
scottmg5e65e3a2017-03-08 08:48:46[diff] [blame]120returnLazyInstanceTraitsBase<Type>::New(instance);
evan@chromium.orgdcc69332010-10-21 20:41:47[diff] [blame]121}
Peter Kasting134ef9af2024-12-28 02:30:09[diff] [blame]122staticvoidDelete(Type* instance){}
evan@chromium.orgdcc69332010-10-21 20:41:47[diff] [blame]123};
124
scottmg5e65e3a2017-03-08 08:48:46[diff] [blame]125template<typenameType>
126structErrorMustSelectLazyOrDestructorAtExitForLazyInstance{};
127
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]128}// namespace internal
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]129
scottmg5e65e3a2017-03-08 08:48:46[diff] [blame]130template<
131typenameType,
132typenameTraits=
133internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]134classLazyInstance{
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]135public:
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]136// Do not define a destructor, as doing so makes LazyInstance a
137// non-POD-struct. We don't want that because then a static initializer will
138// be created to register the (empty) destructor with atexit() under MSVC, for
139// example. We handle destruction of the contained Type class explicitly via
140// the OnExit member function, where needed.
dvyukov@google.com1b651d52011-05-16 15:01:54[diff] [blame]141// ~LazyInstance() {}
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]142
fischman@chromium.org9fc44162012-01-23 22:56:41[diff] [blame]143// Convenience typedef to avoid having to repeat Type for leaky lazy
144// instances.
Joe Downing0d4683d2018-01-24 01:32:38[diff] [blame]145typedefLazyInstance<Type,internal::LeakyLazyInstanceTraits<Type>>Leaky;
146typedefLazyInstance<Type,internal::DestructorAtExitLazyInstanceTraits<Type>>
147DestructorAtExit;
fischman@chromium.org9fc44162012-01-23 22:56:41[diff] [blame]148
Peter Kasting134ef9af2024-12-28 02:30:09[diff] [blame]149Type&Get(){return*Pointer();}
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]150
151Type*Pointer(){
gab190f7542016-08-01 20:03:41[diff] [blame]152#if DCHECK_IS_ON()
Peter Kasting134ef9af2024-12-28 02:30:09[diff] [blame]153if(!Traits::kAllowedToAccessOnNonjoinableThread){
Gabriel Charetted90bcc92021-09-21 00:23:10[diff] [blame]154internal::AssertSingletonAllowed();
Peter Kasting134ef9af2024-12-28 02:30:09[diff] [blame]155}
joth@chromium.org3c7a7f32011-11-04 17:29:10[diff] [blame]156#endif
Gabriel Charettef297f012018-01-17 20:59:07[diff] [blame]157
Gabriel Charetted55aad502018-01-26 18:07:51[diff] [blame]158return subtle::GetOrCreateLazyPointer(
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]159 private_instance_,&Traits::New, private_buf_,
Gabriel Charetted55aad502018-01-26 18:07:51[diff] [blame]160Traits::kRegisterOnExit?OnExit:nullptr,this);
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]161}
162
Lukasz Anforowiczd3e19132017-12-06 19:44:27[diff] [blame]163// Returns true if the lazy instance has been created. Unlike Get() and
164// Pointer(), calling IsCreated() will not instantiate the object of Type.
165boolIsCreated(){
166// Return true (i.e. "created") if |private_instance_| is either being
167// created right now (i.e. |private_instance_| has value of
168// internal::kLazyInstanceStateCreating) or was already created (i.e.
169// |private_instance_| has any other non-zero value).
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]170return0!= private_instance_.load(std::memory_order_relaxed);
dilmah@chromium.org332710b2011-02-22 19:21:59[diff] [blame]171}
172
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]173// MSVC gives a warning that the alignment expands the size of the
174// LazyInstance struct to make the size a multiple of the alignment. This
175// is expected in this case.
Xiaohan Wang38e4ebb2022-01-19 06:57:43[diff] [blame]176#if BUILDFLAG(IS_WIN)
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]177#pragma warning(push)
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]178#pragma warning(disable:4324)
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]179#endif
180
181// Effectively private: member data is only public to allow the linker to
182// statically initialize it and to maintain a POD class. DO NOT USE FROM
183// OUTSIDE THIS CLASS.
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]184 std::atomic<uintptr_t> private_instance_;
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]185
186// Preallocated space for the Type instance.
187 alignas(Type)char private_buf_[sizeof(Type)];
188
Xiaohan Wang38e4ebb2022-01-19 06:57:43[diff] [blame]189#if BUILDFLAG(IS_WIN)
Robert Liao6c58b8702018-02-01 04:47:01[diff] [blame]190#pragma warning(pop)
191#endif
192
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]193private:
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]194Type* instance(){
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]195returnreinterpret_cast<Type*>(
196 private_instance_.load(std::memory_order_relaxed));
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]197}
198
satish@chromium.org625332e02010-12-14 07:48:49[diff] [blame]199// Adapter function for use with AtExit. This should be called single
joth@chromium.org113eee02011-10-25 19:04:48[diff] [blame]200// threaded, so don't synchronize across threads.
satish@chromium.org625332e02010-12-14 07:48:49[diff] [blame]201// Calling OnExit while the instance is in use by other threads is a mistake.
202staticvoidOnExit(void* lazy_instance){
203LazyInstance<Type,Traits>* me=
204reinterpret_cast<LazyInstance<Type,Traits>*>(lazy_instance);
joth@chromium.org6de0fd1d2011-11-15 13:31:49[diff] [blame]205Traits::Delete(me->instance());
Benoit Lizeb82171a62022-06-17 13:37:58[diff] [blame]206 me->private_instance_.store(0, std::memory_order_relaxed);
satish@chromium.org625332e02010-12-14 07:48:49[diff] [blame]207}
deanm@google.com30039e62008-09-08 14:11:13[diff] [blame]208};
209
210}// namespace base
211
212#endif// BASE_LAZY_INSTANCE_H_

[8]ページ先頭

©2009-2025 Movatter.jp