Breaking News
Loading...
Sunday, 11 February 2007

Service Configurator pattern and singleton deletion

12:05
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 {
protected:
Singleton ();
public:
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.
}
protected:
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.

0 comments:

Post a Comment

 
Toggle Footer