Orxonox  0.0.5 Codename: Arcturus
Classes | Namespaces
Singleton.h File Reference

Definition of the Singleton template that is used as base class for classes that allow only one instance. More...

#include "UtilPrereqs.h"
#include <cstring>
#include <typeinfo>
#include "OrxAssert.h"

Go to the source code of this file.

Classes

class  orxonox::Singleton< T >
 Base for singleton classes. More...
 

Namespaces

 orxonox
 Die Wagnis Klasse hat die folgenden Aufgaben:
 

Detailed Description

Definition of the Singleton template that is used as base class for classes that allow only one instance.

Classes that inherit from orxonox::Singleton follow the singleton pattern and thus allow only one instance of the class to exist. This istance is stored in a static variable called singletonPtr_s. orxonox::Singleton will access this variable, but it must be implemented in the deriving class.

Example:

class TestSingleton : public Singleton<TestSingleton> // inherit from Singleton, pass the own class as template argument
{
friend class Singleton<TestSingleton>; // friend declaration so Singleton can access singletonPtr_s
public:
TestSingleton(); // public constructor because we may want to manage this singleton
// with an orxonox::ScopedSingletonWrapper
virtual ~TestSingleton(); // public destructor
void testFunction(); // put your functions here
private:
int testValue_; // put your variables here
static TestSingleton* singletonPtr_s; // static singleton instance pointer, used by the Singleton template
};

And don't forget to initialize the static singleton pointer in the source (*.cc) file:

TestSingleton* TestSingleton::singletonPtr_s = nullptr;

If a class inherits from orxonox::Singleton, it also inherits its functions. The most important function is orxonox::Singleton::getInstance() which returns a reference to the only instance of the singleton.

Example:

TestSingleton::TestSingleton() // implement the constructor
{
this->testValue_ = 15;
}
void TestSingleton::testFunction() // implement testFunction
{
orxout() << "My value is " << this->testValue_ << endl;
}
TestSingleton::getInstance().testFunction(); // prints "My value is 15"