Fix folly::Singleton to work with objects w/o default constructor
authorAndrii Grynenko <andrii@fb.com>
Wed, 17 Sep 2014 04:12:10 +0000 (21:12 -0700)
committerAndrii Grynenko <andrii@fb.com>
Wed, 15 Oct 2014 00:52:44 +0000 (17:52 -0700)
Test Plan:
unit tests

Reviewed By: ostap@fb.com

Subscribers: netego-diffs@, trunkagent, alikhtarov, marccelani, mshneer, zhuohuang, lins, njormrod

FB internal diff: D1560406

folly/experimental/Singleton.h

index c2100e0d90773a7009b75d8fbc5eb67d0c1831f6..524e5217f845303b50dc52f456a72a7e412a7d6a 100644 (file)
@@ -415,25 +415,38 @@ class Singleton {
   T& operator*() { return *ptr(); }
   T* operator->() { return ptr(); }
 
-  explicit Singleton(Singleton::CreateFunc c = nullptr,
+  template <typename CreateFunc = std::nullptr_t>
+  explicit Singleton(CreateFunc c = nullptr,
                      Singleton::TeardownFunc t = nullptr,
                      SingletonVault* vault = nullptr /* for testing */)
       : Singleton({typeid(T), ""}, c, t, vault) {}
 
+  template <typename CreateFunc = std::nullptr_t>
   explicit Singleton(const char* name,
-                     Singleton::CreateFunc c = nullptr,
+                     CreateFunc c = nullptr,
                      Singleton::TeardownFunc t = nullptr,
                      SingletonVault* vault = nullptr /* for testing */)
       : Singleton({typeid(T), name}, c, t, vault) {}
 
  private:
   explicit Singleton(detail::TypeDescriptor type,
-                     Singleton::CreateFunc c = nullptr,
-                     Singleton::TeardownFunc t = nullptr,
-                     SingletonVault* vault = nullptr /* for testing */)
+                     std::nullptr_t,
+                     Singleton::TeardownFunc t,
+                     SingletonVault* vault) :
+      Singleton (type,
+                 []() { return new T; },
+                 std::move(t),
+                 vault) {
+  }
+
+  explicit Singleton(detail::TypeDescriptor type,
+                     Singleton::CreateFunc c,
+                     Singleton::TeardownFunc t,
+                     SingletonVault* vault)
       : type_descriptor_(type) {
     if (c == nullptr) {
-      c = []() { return new T; };
+      throw std::logic_error(
+        "nullptr_t should be passed if you want T to be default constructed");
     }
     SingletonVault::TeardownFunc teardown;
     if (t == nullptr) {