Drake
scoped_singleton.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <memory>
4 #include <mutex>
5 
8 
9 namespace drake {
10 
23 template <typename T, typename Unique = void>
24 std::shared_ptr<T> GetScopedSingleton() {
25  // Confine implementation to a class.
26  class Singleton {
27  public:
29 
30  Singleton() {}
31 
32  /*
33  * Acquire a reference to resource if no other instance exists.
34  * Otherwise, return a shared reference to the resource.
35  */
36  std::shared_ptr<T> Acquire() {
37  // Acquiring and releasing the resource via a centralized weak pointer,
38  // will be thread-safe. All constructions of T for this particular
39  // Singleton are assigned to this same weak_ref_; the empty-check,
40  // allocation, and weak_ref_ assignment are all guarded by the same
41  // critical section.
42  auto instance = weak_ref_.lock();
43  if (!instance) {
44  instance = std::make_shared<T>();
45  weak_ref_ = instance;
46  }
47  return instance;
48  }
49 
50  private:
51  std::weak_ptr<T> weak_ref_;
52  };
53  // Allocate singleton as a static function local to control initialization.
54  static never_destroyed<Singleton> singleton;
55  return singleton.access().Acquire();
56 }
57 
58 } // namespace drake
Definition: automotive_demo.cc:88
#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:35
Provides careful macros to selectively enable or disable the special member functions for copy-constr...