From 26537d7028afe67bcf78c24374f948f4f1fddc6b Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 23 Sep 2011 14:26:53 +0000 Subject: [PATCH] Utils: Singleton template and migration of the BufferManager Singletons are not autocreating, the application needs to create exactly one instance (I want to avoid implicit initialization order hell) --- src/buffer_manager.cc | 20 -------------------- src/buffer_manager.hh | 8 ++------ src/main.cc | 1 + src/utils.hh | 40 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 26 deletions(-) diff --git a/src/buffer_manager.cc b/src/buffer_manager.cc index eb75c3a7..27187080 100644 --- a/src/buffer_manager.cc +++ b/src/buffer_manager.cc @@ -10,26 +10,6 @@ namespace Kakoune struct name_not_unique : logic_error {}; -BufferManager* BufferManager::ms_instance = nullptr; - -BufferManager& BufferManager::instance() -{ - if (not ms_instance) - ms_instance = new BufferManager(); - - return *ms_instance; -} - -void BufferManager::delete_instance() -{ - delete ms_instance; - ms_instance = nullptr; -} - -BufferManager::BufferManager() -{ -} - void BufferManager::register_buffer(Buffer* buffer) { assert(buffer); diff --git a/src/buffer_manager.hh b/src/buffer_manager.hh index b0cd9518..126b41a3 100644 --- a/src/buffer_manager.hh +++ b/src/buffer_manager.hh @@ -2,6 +2,7 @@ #define buffer_manager_hh_INCLUDED #include "buffer.hh" +#include "utils.hh" #include #include @@ -9,7 +10,7 @@ namespace Kakoune { -class BufferManager +class BufferManager : public Singleton { public: typedef std::unordered_map> BufferMap; @@ -32,12 +33,7 @@ public: Buffer* get_buffer(const std::string& name); - static BufferManager& instance(); - static void delete_instance(); - private: - BufferManager(); - static BufferManager* ms_instance; BufferMap m_buffers; }; diff --git a/src/main.cc b/src/main.cc index ea976a45..b21737ac 100644 --- a/src/main.cc +++ b/src/main.cc @@ -329,6 +329,7 @@ void show_buffer(const CommandParameters& params) } CommandManager command_manager; +BufferManager buffer_manager; void do_command() { diff --git a/src/utils.hh b/src/utils.hh index 5f6e93a5..fcc7a77a 100644 --- a/src/utils.hh +++ b/src/utils.hh @@ -2,6 +2,7 @@ #define utils_hh_INCLUDED #include "exception.hh" +#include "assert.hh" #include @@ -59,6 +60,45 @@ AutoRaii auto_raii(T* resource, F cleanup) return AutoRaii(resource, cleanup); } +template +class Singleton +{ +public: + Singleton(const Singleton&) = delete; + Singleton& operator=(const Singleton&) = delete; + + static T& instance() + { + assert (ms_instance); + return *ms_instance; + } + + static void delete_instance() + { + if (ms_instance) + delete ms_instance; + } + +protected: + Singleton() + { + assert(not ms_instance); + ms_instance = static_cast(this); + } + + ~Singleton() + { + assert(ms_instance == this); + ms_instance = nullptr; + } + +private: + static T* ms_instance; +}; + +template +T* Singleton::ms_instance = nullptr; + } #endif // utils_hh_INCLUDED