Drake
never_destroyed.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <new>
4 #include <type_traits>
5 #include <utility>
6 
8 
9 namespace drake {
10 
11 /// Wraps an underlying type T such that its storage is a direct member field
12 /// of this object (i.e., without any indirection into the heap), but *unlike*
13 /// most member fields T's destructor is never invoked.
14 ///
15 /// This is especially useful for function-local static variables that are not
16 /// trivially destructable. We shouldn't call their destructor at program exit
17 /// because of the "indeterminate order of ... destruction" as mentioned in
18 /// cppguide's #Static_and_Global_Variables section, but other solutions to
19 /// this problem place the objects on the heap through an indirection.
20 ///
21 /// Compared with other approaches, this mechanism more clearly describes the
22 /// intent to readers, avoids "possible leak" warnings from memory-checking
23 /// tools, and is probably slightly faster.
24 template <typename T>
26  public:
28 
29  /// Passes the constructor arguments along to T using perfect forwarding.
30  template <typename... Args>
31  explicit never_destroyed(Args&&... args) {
32  // Uses "placement new" to construct a `T` in `storage_`.
33  new (&storage_) T(std::forward<Args>(args)...);
34  }
35 
36  /// Does nothing. Guaranteed!
37  ~never_destroyed() = default;
38 
39  /// Returns the underlying T reference.
40  T& access() { return *reinterpret_cast<T*>(&storage_); }
41  const T& access() const { return *reinterpret_cast<const T*>(&storage_); }
42 
43  private:
44  typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;
45 };
46 
47 } // namespace drake
never_destroyed(Args &&...args)
Passes the constructor arguments along to T using perfect forwarding.
Definition: never_destroyed.h:31
~never_destroyed()=default
Does nothing. Guaranteed!
Definition: automotive_demo.cc:88
const T & access() const
Definition: never_destroyed.h:41
#define DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Classname)
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN deletes the special member functions for copy-construction, copy-assignment, move-construction, and move-assignment.
Definition: drake_copyable.h:33
Wraps an underlying type T such that its storage is a direct member field of this object (i...
Definition: never_destroyed.h:25
Provides careful macros to selectively enable or disable the special member functions for copy-constr...
T & access()
Returns the underlying T reference.
Definition: never_destroyed.h:40