tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

no_destructor.h (5009B)


      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.
      4 
      5 #ifndef BASE_NO_DESTRUCTOR_H_
      6 #define BASE_NO_DESTRUCTOR_H_
      7 
      8 #include <new>
      9 #include <type_traits>
     10 #include <utility>
     11 
     12 namespace base {
     13 
     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.
     17 //
     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.
     22 //
     23 // ## Caveats
     24 //
     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.
     29 //
     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.
     34 //
     35 // - If `T` is trivially destructible, do not use `base::NoDestructor<T>`:
     36 //
     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;
     42 //     }
     43 //
     44 // ## Example Usage
     45 //
     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!");
     49 //   return *s;
     50 // }
     51 //
     52 // More complex initialization using a lambda:
     53 //
     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([] {
     58 //     std::string s(16);
     59 //     crypto::RandString(s.data(), s.size());
     60 //     return s;
     61 //   }());
     62 //   return *nonce;
     63 // }
     64 //
     65 // ## Thread safety
     66 //
     67 // Initialisation of function-local static variables is thread-safe since C++11.
     68 // The standard guarantees that:
     69 //
     70 // - function-local static variables will be initialised the first time
     71 //   execution passes through the declaration.
     72 //
     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.
     76 template <typename T>
     77 class NoDestructor {
     78 public:
     79  static_assert(
     80      !std::is_trivially_destructible_v<T>,
     81      "T is trivially destructible; please use a function-local static "
     82      "of type T directly instead");
     83 
     84  // Not constexpr; just write static constexpr T x = ...; if the value should
     85  // be a constexpr.
     86  template <typename... Args>
     87  explicit NoDestructor(Args&&... args) {
     88    new (storage_) T(std::forward<Args>(args)...);
     89  }
     90 
     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)); }
     95 
     96  NoDestructor(const NoDestructor&) = delete;
     97  NoDestructor& operator=(const NoDestructor&) = delete;
     98 
     99  ~NoDestructor() = default;
    100 
    101  const T& operator*() const { return *get(); }
    102  T& operator*() { return *get(); }
    103 
    104  const T* operator->() const { return get(); }
    105  T* operator->() { return get(); }
    106 
    107  const T* get() const { return reinterpret_cast<const T*>(storage_); }
    108  T* get() { return reinterpret_cast<T*>(storage_); }
    109 
    110 private:
    111  alignas(T) char storage_[sizeof(T)];
    112 
    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.
    121  //
    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)
    128 };
    129 
    130 }  // namespace base
    131 
    132 #endif  // BASE_NO_DESTRUCTOR_H_