Sunday, February 11, 2007

Service Configurator pattern and singleton deletion

The Service Configurator pattern is about linking in additional functionality in an application dynamically by means of an API such as dlsym/dlopen provided by the OS/run-time linker. Almost all popular platforms provide this functionality. This post is about programmatically, dynamically loaded libraries (hence forth called simply library)(e.g., .DLL, .so) that contain sigletons.

One of my previous posts talks about singleton deletion. If the sinlgleton in such a library is a static instance then it is not deleted untill the library is closed using appropriate API such as dlclose. This can be quite undesirable or awkward at times. All the destruction techniques based on static variables fail if you want to destroy the singleton without unloading the library. A possible variant of the singleton in such a case is given below.

class Singleton {
Singleton ();
static Singleton *instance () {
if (instance_ == 0)
instance_ = new Singleton;
return instance_;
static void operator delete (void *arg) // operator delete is implicitely static
::delete arg; // Call the global delete operator.
instance_ = 0; // A very important step.
static Singleton * instance_;
Singleton * Singleton::instance_ = 0;

The overloaded delete operator allows us to nullify the static instance_ pointer to the singleton transperantly to the user/owner of the sinlgeton. If the singleton is required again then can be instantiated again. The owner of the singleton can use the const auto_ptr idiom to ensure that the ownership of the singleton is never transferred and it is always deleted.


Anonymous said...

How is the static delete operator invoked?

Sumant said...

The operator delete is invoked as you would do for any other dynamically allocated object.
for example, delete Singleton::instance();
Or else
{ // for automatic deletion
const std::auto_ptr owner(Singleton::instance());

Web development said...

What nice and professional article you have held, really you have impressed me. I respect your comment from my bottom of heart.

descargar anime said...

Hello, this is my first comment on this blog and I wanted to say that I'm really amazed with this blog after reading this article about C++ in which I share your same opinion. I will definitely bookmark this page!

manho valentine said...

Anonymous Anonymous said...
How is the static delete operator invoked?