singleton.h File Reference

Manage a single instance of an object. More...

+ Include dependency graph for singleton.h:
+ This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  TfSingleton< T >
 Manage a single instance of an object (see. More...
 

Detailed Description

Manage a single instance of an object.

Many classes (for example, registries) should have only a single, globally available instance that is created as needed on demand. This is a classic design pattern known as a singleton. Additionally, creation of this class (though not access to it per se) must be made threadsafe.

There are two possibilities in creating a singleton: you can create a class all of whose member functions and variables are static, and let users access this class. Unfortunately, instantiating the static variables of this class is prone to difficulty; more importantly, should you change your mind and wish to allow multiple instances of the class, much rewriting follows.

A better solution is to define the class with regular members and variables, and then permit only a single instance of the class to exist. This is the philosophy embodied by the TfSingleton template. It takes care of both multithreaded initialization and initialization before main; the cost of this is quite low (a single boolean comparison to access the instanced object after initial creation). The TfSingleton template works in conjunction with a macro in the source file TF_INSTANTIATE_SINGLETON(), which is itself defined by including the file "pxr/base/tf/instantiateSingleton.h".

Typical Use

The typical use of TfSingleton is as follows:

// file: registry.h
#include <boost/noncopyable.hpp>
class Registry : boost::noncopyable {
public:
static Registry& GetInstance() {
}
...
private:
Registry();
~Registry();
friend class TfSingleton<Registry>;
};
// file: Registry.cpp
#include "common/astrology/registry.h"
// file: RandomCode.cpp
#include "common/astrology/registry.h"
void Code() {
Registry& r = Registry::GetInstance();
r.Lookup(...);
...
}

The constructor and destructor are declared private, and the singleton object will typically derive off of boost::noncopyable to prevent copying. Note that singleton objects quite commonly also make use of TfRegistryManager to acquire the data they need throughout a program.

The friend class TfSingleton<Registry> is the only class allowed to create an instance of a Registry. The helper function Registry::GetInstance() is for convenience only; one can just as well call the longer TfSingleton<Registry>::GetInstance() to obtain a reference to the sole instance of the registry.

Definition in file singleton.h.