Для получения полного доступа
зарегистрируйтесь.
Snippet,  C++

Base class for creating Phoenix Singleton classes with dependencies being handled automatically


A base class that can be used if you want to create a hierarchy of phoenix singletons. The task of handling dependencies properly is done automatically. C++11 is used. Syntax: class YourPhoenix : Phoenix < YourClass, ListOfDependencies... >

Usage: declare your phoenix singleton class to be a child of Phoenix and make getPhoenix function to be a friend of your Phoenix class. Well, that's it. Construction is made in constructor and destruction is made in destructor. No more effort is needed.

Phoenix: die when forgotten, revive on demand.

#include <memory>

template<class S>
std::shared_ptr<S> getPhoenix() {
    static std::weak_ptr<S> singleton = { };
	
    if(singleton.expired()) {
        std::shared_ptr<S> sharedObject { new S() };
        singleton = { sharedObject };
        return sharedObject;
    }
	
    return singleton.lock();
}

template<class S, class ... D> class Phoenix { };
template<class S, class C, class ... D> class Phoenix<S, C, D...> : Phoenix<S, D...> {
    std::shared_ptr<C> _reference;
protected:
    Phoenix() : _reference { getPhoenix<C>() } { }
};
  c++ challenge singleton

Автор


Gravatar image
relacc
  • Reputation: 2
  • Snippets : 1
  • Revisions : 0
Подписаться

Чтобы увидеть комментарии, нужно быть участником сообщества

Регистрация