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