This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Singleton instantiated more than once with -fvisibility=hidden


On Friday 03 June 2005 15:09, Filipe Sousa wrote:
> On Friday 03 June 2005 13:46, Mws wrote:
> > hi,
> >
> > in my understanding a singleton is used to have a class
> > instanciated only for one time.
> >
> > normally this is done by
> >
> > having the "wanted-to-be-singleton-class" derived/inherited from
> > a singleton class or template.
> > never ever from the outside ctors are called, but there should be
> > a getInstance() method that checks for _m_instance == NULL
> > if it is matching creating a new instance with new, otherwise returning the
> > _m_instance pointer.
> 
> A templated version
> 
> template<class T>
> class singleton {
> public:
>     static T* instance() {
>         if (!m_instance)
>             m_instance = new T;
>         return m_instance;
>     }
> 
> private:
>     static  __attribute__ ((visibility("default"))) T* m_instance;
> };
> 
> class __attribute__ ((visibility("default"))) my_singleton : public 
> singleton<my_singleton> {
> public:
>     my_singleton() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
> };
> 
> > if you want to, i can provide you with a complete singleton template.
> 
> Yes, please
> 
> > regards
> > mws
> 
> 

singleton.h

#ifndef __singleton__
#define __singleton__

template<class IMPLEMENTINGCLASS>
class TSingleton
{
	private:
		static IMPLEMENTINGCLASS* instance;

	public:
		static IMPLEMENTINGCLASS* getInstance()
		{
			//debugging purposes
			std::cout << "before" << instance << std::endl;
			if(!instance)
			{
				instance = new IMPLEMENTINGCLASS();
			}
			std::cout << "after" << instance << std::endl;
			return instance;
		}

		void dispose()
		{
			if(instance)
			{
				delete instance;
				instance = NULL;
			}
		}
};

template<class IMPLEMENTINGCLASS> IMPLEMENTINGCLASS* TSingleton<IMPLEMENTINGCLASS>::instance = NULL;

#endif

usage is like

class CFoo:public TSingleton<foo>
{
	private:
		CFoo();
		virtual ~CFoo();

	public:

		...
		...

};

in case of debugging this you should do a std::cout << instance << std::endl;
instead of mentioning that the ctor is called.


int main() {
    // get the instance 
    CFoo::getInstance();
    CFoo::getInstance();

    // free mem - call dtor
    CFoo::dispose(); 

    return 0;
}

that's what i would do

regards
mws

Attachment: pgp00000.pgp
Description: PGP signature


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]