Tuesday, 15 March 2011

C++ Singleton design pattern -



C++ Singleton design pattern -

recently i've bumped realization/implementation of singleton design pattern c++. has looked (i have adopted real life example):

// lot of methods omitted here class singleton { public: static singleton* getinstance( ); ~singleton( ); private: singleton( ); static singleton* instance; };

from declaration can deduce instance field initiated on heap. means there memory allocation. unclear me when memory going deallocated? or there bug , memory leak? seems there problem in implementation.

my main question is, how implement in right way?

see article simple design lazy evaluated guaranteed destruction singleton: can 1 provide me sample of singleton in c++?

the classic lazy evaluated , correctly destroyed singleton.

class s { public: static s& getinstance() { static s instance; // guaranteed destroyed. // instantiated on first use. homecoming instance; } private: s() {}; // constructor? (the {} brackets) needed here. // c++ 03 // ======== // dont forget declare these two. want create sure // unacceptable otherwise may accidentally copies of // singleton appearing. s(s const&); // don't implement void operator=(s const&); // don't implement // c++ 11 // ======= // can utilize improve technique of deleting methods // don't want. public: s(s const&) = delete; void operator=(s const&) = delete; // note: scott meyers mentions in effective modern // c++ book, deleted functions should // public results in improve error messages // due compilers behavior check accessibility // before deleted status };

see article when utilize singleton: (not often) singleton: how should used

see 2 article initialization order , how cope: static variables initialisation order finding c++ static initialization order problems

see article describing lifetimes: what lifetime of static variable in c++ function?

see article discusses threading implications singletons: singleton instance declared static variable of getinstance method

see article explains why double checked locking not work on c++: what mutual undefined behaviours c++ programmer should know about?

c++ design-patterns singleton

No comments:

Post a Comment