From f1aa0df4c3bb90faba7d9203312f043fd59dec9d Mon Sep 17 00:00:00 2001 From: Vlad Zolotarov Date: Mon, 1 Jun 2015 11:31:49 +0300 Subject: [PATCH] class_registrator: ensure the static member initialization order There was a possibility for initialization disorder of static member _classes and its usage in another static class. Defining the _classes inside the static method that is called when it's accessed ensures the proper initialization (aka "standard trick", quoting Avi ;)). Signed-off-by: Vlad Zolotarov --- utils/class_registrator.hh | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/utils/class_registrator.hh b/utils/class_registrator.hh index 31c4ed1e85..a6158fab7b 100644 --- a/utils/class_registrator.hh +++ b/utils/class_registrator.hh @@ -14,20 +14,22 @@ public: template class class_registry { using creator_type = std::function(Args...)>; - static std::unordered_map _classes; public: static void register_class(sstring name, creator_type creator); template static void register_class(sstring name); static std::unique_ptr create(const sstring& name, Args...); + + static std::unordered_map& classes() { + static std::unordered_map _classes; + + return _classes; + } }; -template -std::unordered_map::creator_type> class_registry::_classes; - template void class_registry::register_class(sstring name, class_registry::creator_type creator) { - _classes.emplace(name, std::move(creator)); + classes().emplace(name, std::move(creator)); } template @@ -50,8 +52,8 @@ struct class_registrator { template std::unique_ptr class_registry::create(const sstring& name, Args... args) { - auto it = _classes.find(name); - if (it == _classes.end()) { + auto it = classes().find(name); + if (it == classes().end()) { throw no_such_class(sstring("unable to find class '") + name + sstring("'")); } return it->second(args...);