1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_NO_DESTRUCTOR_H_
6 #define BASE_NO_DESTRUCTOR_H_
14 // Helper type to create a function-local static variable of type `T` when `T`
15 // has a non-trivial destructor. Storing a `T` in a `base::NoDestructor<T>` will
16 // prevent `~T()` from running, even when the variable goes out of scope.
18 // Useful when a variable has static storage duration but its type has a
19 // non-trivial destructor. Chromium bans global constructors and destructors:
20 // using a function-local static variable prevents the former, while using
21 // `base::NoDestructor<T>` prevents the latter.
25 // - Must only be used as a function-local static variable. Declaring a global
26 // variable of type `base::NoDestructor<T>` will still generate a global
27 // constructor; declaring a local or member variable will lead to memory leaks
28 // or other surprising and undesirable behaviour.
30 // - If the data is rarely used, consider creating it on demand rather than
31 // caching it for the lifetime of the program. Though `base::NoDestructor<T>`
32 // does not heap allocate, the compiler still reserves space in bss for
33 // storing `T`, which costs memory at runtime.
35 // - If `T` is trivially destructible, do not use `base::NoDestructor<T>`:
37 // const uint64_t GetUnstableSessionSeed() {
38 // // No need to use `base::NoDestructor<T>` as `uint64_t` is trivially
39 // // destructible and does not require a global destructor.
40 // static const uint64_t kSessionSeed = base::RandUint64();
41 // return kSessionSeed;
46 // const std::string& GetDefaultText() {
47 // // Required since `static const std::string` requires a global destructor.
48 // static const base::NoDestructor<std::string> s("Hello world!");
52 // More complex initialization using a lambda:
54 // const std::string& GetRandomNonce() {
55 // // `nonce` is initialized with random data the first time this function is
56 // // called, but its value is fixed thereafter.
57 // static const base::NoDestructor<std::string> nonce([] {
59 // crypto::RandString(s.data(), s.size());
67 // Initialisation of function-local static variables is thread-safe since C++11.
68 // The standard guarantees that:
70 // - function-local static variables will be initialised the first time
71 // execution passes through the declaration.
73 // - if another thread's execution concurrently passes through the declaration
74 // in the middle of initialisation, that thread will wait for the in-progress
75 // initialisation to complete.
80 !std::is_trivially_destructible_v<T>,
81 "T is trivially destructible; please use a function-local static "
82 "of type T directly instead");
84 // Not constexpr; just write static constexpr T x = ...; if the value should
86 template <typename... Args>
87 explicit NoDestructor(Args&&... args) {
88 new (storage_) T(std::forward<Args>(args)...);
91 // Allows copy and move construction of the contained type, to allow
92 // construction from an initializer list, e.g. for std::vector.
93 explicit NoDestructor(const T& x) { new (storage_) T(x); }
94 explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); }
96 NoDestructor(const NoDestructor&) = delete;
97 NoDestructor& operator=(const NoDestructor&) = delete;
99 ~NoDestructor() = default;
101 const T& operator*() const { return *get(); }
102 T& operator*() { return *get(); }
104 const T* operator->() const { return get(); }
105 T* operator->() { return get(); }
107 const T* get() const { return reinterpret_cast<const T*>(storage_); }
108 T* get() { return reinterpret_cast<T*>(storage_); }
111 alignas(T) char storage_[sizeof(T)];
113 #if defined(LEAK_SANITIZER)
114 // TODO(https://crbug.com/812277): This is a hack to work around the fact
115 // that LSan doesn't seem to treat NoDestructor as a root for reachability
116 // analysis. This means that code like this:
117 // static base::NoDestructor<std::vector<int>> v({1, 2, 3});
118 // is considered a leak. Using the standard leak sanitizer annotations to
119 // suppress leaks doesn't work: std::vector is implicitly constructed before
120 // calling the base::NoDestructor constructor.
122 // Unfortunately, I haven't been able to demonstrate this issue in simpler
123 // reproductions: until that's resolved, hold an explicit pointer to the
124 // placement-new'd object in leak sanitizer mode to help LSan realize that
125 // objects allocated by the contained type are still reachable.
126 T* storage_ptr_ = reinterpret_cast<T*>(storage_);
127 #endif // defined(LEAK_SANITIZER)
132 #endif // BASE_NO_DESTRUCTOR_H_