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)
This commit is contained in:
Maxime Coste 2011-09-23 14:26:53 +00:00
parent 52ad372adb
commit 26537d7028
4 changed files with 43 additions and 26 deletions

View File

@ -10,26 +10,6 @@ namespace Kakoune
struct name_not_unique : logic_error {}; 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) void BufferManager::register_buffer(Buffer* buffer)
{ {
assert(buffer); assert(buffer);

View File

@ -2,6 +2,7 @@
#define buffer_manager_hh_INCLUDED #define buffer_manager_hh_INCLUDED
#include "buffer.hh" #include "buffer.hh"
#include "utils.hh"
#include <unordered_map> #include <unordered_map>
#include <memory> #include <memory>
@ -9,7 +10,7 @@
namespace Kakoune namespace Kakoune
{ {
class BufferManager class BufferManager : public Singleton<BufferManager>
{ {
public: public:
typedef std::unordered_map<std::string, std::unique_ptr<Buffer>> BufferMap; typedef std::unordered_map<std::string, std::unique_ptr<Buffer>> BufferMap;
@ -32,12 +33,7 @@ public:
Buffer* get_buffer(const std::string& name); Buffer* get_buffer(const std::string& name);
static BufferManager& instance();
static void delete_instance();
private: private:
BufferManager();
static BufferManager* ms_instance;
BufferMap m_buffers; BufferMap m_buffers;
}; };

View File

@ -329,6 +329,7 @@ void show_buffer(const CommandParameters& params)
} }
CommandManager command_manager; CommandManager command_manager;
BufferManager buffer_manager;
void do_command() void do_command()
{ {

View File

@ -2,6 +2,7 @@
#define utils_hh_INCLUDED #define utils_hh_INCLUDED
#include "exception.hh" #include "exception.hh"
#include "assert.hh"
#include <memory> #include <memory>
@ -59,6 +60,45 @@ AutoRaii<T, F> auto_raii(T* resource, F cleanup)
return AutoRaii<T, F>(resource, cleanup); return AutoRaii<T, F>(resource, cleanup);
} }
template<typename T>
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<T*>(this);
}
~Singleton()
{
assert(ms_instance == this);
ms_instance = nullptr;
}
private:
static T* ms_instance;
};
template<typename T>
T* Singleton<T>::ms_instance = nullptr;
} }
#endif // utils_hh_INCLUDED #endif // utils_hh_INCLUDED