c++ - Prevent duplicate objects in classes/instance access with singleton -


the use provide .instance access, prevent duplicate objects of classes.

is code implementation of singleton?

template <typename t> class singleton { public:     static t *ms_singleton;      singleton()     {         assert(!ms_singleton);         long offset = (long)(t *) 1 - (long)(singleton <t> *)(t *) 1;         ms_singleton = (t *)((long) + offset);     }      virtual ~singleton()     {         assert(ms_singleton);         ms_singleton = 0;     }      static t &instance()     {         assert(ms_singleton);         return (*ms_singleton);     }      static t &instance()     {         assert(ms_singleton);         return (*ms_singleton);     }      static t *instance_ptr()     {         return (ms_singleton);     } }; template <typename t> t *singleton <t>::ms_singleton = null; 

how use it:

class test1: public singleton<test2> {     // }; 

if not, wrong here? should rewrite here?

your singleton class has weird things. relying on constructor debug-build run-time check can constructed or not, in constructor.

a typical singleton class have constructors private can constructed accessor function. should not rely on e.g. assert macro disabled in release builds.

a simple non-inheritable singleton class this:

class singleton { public:     static singleton& instance()     {         static singleton actual_instance;         return actual_instance;     }      // other public member functions  private:     // private constructor     singleton() = default; }; 

by having constructor private, means no 1 else can't attempt construct instance. means checked @ time of compilation compiler itself.

also having actual instance of object static variable and initialized @ definition inside accessor function, mean creation of instance thread-safe.


to expand , make generic seem want do, need make base class constructor protected. need make base class friend in inherited class.

the child-class still need make constructor private prevent accidental construction.

updated base class like

template<typename t> class singleton { public:     static t& instance()     {         static t actual_instance;         return actual_instance;     }  protected:     singleton() = default; }; 

a child class might like

class childsingleton : public singleton<childsingleton> { public:     // public member functions...  private:     friend class singleton<childsingleton>;      // private constructor     childsingleton() = default; }; 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -