Boost logo

Boost Users :

From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2007-01-22 12:29:53


I might be wrong here, but I would like to hear some thoughts of C++ professionals.

I read in lots of sources about DCLP and how it is broken in conjunction with Singleton pattern
and my question is of a very simple nature. Is it possible to solve this problem by introducing
function calls via function pointers? Or is there still a way, that these calls might be inlined
and if yes then how could this look like? This example is not about freeing the singleton, it is
just about creating it.

class Singleton;
typedef Singleton* (*singleton_getter)();

class Singleton : boost::noncopyable
{
   static Singleton* pInstance;
   static singleton_getter getter;

   //other internal data...

   Singleton();

   static Singleton* creating_singleton_getter();
   static Singleton* non_creating_singleton_getter();

public:
   static Singleton* instance();
};

//implementation
Singleton* Singleton::pInstance = NULL;
singleton_getter Singleton::getter = &creating_singleton_getter;

Singleton::Singleton()
{}

Singleton* Singleton::creating_singleton_getter()
{
        //aquire mutex here
        if(Singleton::pInstance==NULL)
                Singleton::pInstance = new Singleton;
        Singleton::getter = &non_creating_singleton_getter;
        return Singleton::pInstance;
} //mutex unlocked

Singleton* Singleton::non_creating_singleton_getter()
{
        //no mutex anymore
        return Singleton::pInstance;
}

Singleton* Singleton::instance()
{
        return (Singleton::getter)();
}

With Kind Regards,

Ovanes Markarian


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net