SingeltonVault::ScopedExpunger - RAII class to clear singletons
authorYedidya Feldblum <yfeldblum@fb.com>
Sat, 9 Jan 2016 02:40:42 +0000 (18:40 -0800)
committerfacebook-github-bot-4 <folly-bot@fb.com>
Sat, 9 Jan 2016 03:20:24 +0000 (19:20 -0800)
Summary:
[Folly] `SingeltonVault::ScopedExpunger` - RAII class to clear singletons.

Clears all singletons in the given vault at ctor and dtor times. Useful for unit-tests that need to clear the world.

This need can arise when a unit-test needs to swap out an object used by a singleton for a test-double, but the singleton needing its dependency to be swapped has a type or a tag local to some other translation unit and unavailable in the current translation unit.

Other, better approaches to this need are "plz 2 refactor" ....

Reviewed By: andriigrynenko

Differential Revision: D2802459

fb-gh-sync-id: c24cebd3a464ed5da29ea1d9e7b86c51d61cf631

folly/Singleton.h

index a4fdf2036a00ef72c7d9ca92c355fe9406b0a65d..20a043d715dc456c8962dca15bc23851f9d07a22 100644 (file)
@@ -312,6 +312,27 @@ class SingletonVault {
     Relaxed, // Singletons can be created before registrationComplete()
   };
 
+  /**
+   * Clears all singletons in the given vault at ctor and dtor times.
+   * Useful for unit-tests that need to clear the world.
+   *
+   * This need can arise when a unit-test needs to swap out an object used by a
+   * singleton for a test-double, but the singleton needing its dependency to be
+   * swapped has a type or a tag local to some other translation unit and
+   * unavailable in the current translation unit.
+   *
+   * Other, better approaches to this need are "plz 2 refactor" ....
+   */
+  struct ScopedExpunger {
+    SingletonVault* vault;
+    explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
+    ~ScopedExpunger() { expunge(); }
+    void expunge() {
+      vault->destroyInstances();
+      vault->reenableInstances();
+    }
+  };
+
   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
 
   // Destructor is only called by unit tests to check destroyInstances.