singleton


A design may require multiple objects to have visibility to a single instance of a class, but creating the instance globally is bad design. The Singleton pattern solves this common problem. However, rather than creating a derived class that possesses singleton behavior (thus increasing the number of classes needlessly), the better solution would be to supply to the class to a singleton template and use the singleton directly. This is provides less maintenance, provides more flexibility, and can be applied to any class.

The os_singleton class is comprised of only one static member function that returns a pointer to a static instance of type T . To access the singleton, use the static method os_singleton< T >::instance() . The scope of the (singleton, type) combination will be the lifetime of the process, and only one instance of the (singleton, type) combination is created.

Use of template gives the flexibility of not having the original classes to inherit from a specific interface class.

In the following example, a single global instance of the TaskManager class is defined using the singleton class. The very first call to TaskMgr::instance() creates a TaskManager object on the heap and returns it. Subsequent calls return the same pointer as shown in the output.

Example <ospace/framework/examples/singleton1.cpp>
#include <iostream>
#include <ospace/framework.h>

class TaskManager
  {
  public:
    ~TaskManager()
      {
      cout << "TaskManager is getting the ax" << endl;
      }

    void run()
      {
      cout << "TaskManager is running tasks" << endl;
      }
  };


int
main()
  {
  os_framework_toolkit init_framework;

  typedef os_singleton< TaskManager > TaskMgr;

  cout << "Each call to singleton TaskMgr::instance() returns the\n";
  cout << "same TaskManager object pointer:" << endl;

  for ( int i = 0; i < 6; ++i )
    cout << "TaskManager object pointer = "
      << (void*) TaskMgr::instance() << endl;

  TaskMgr::instance()->run();

  cout << "The singleton's resources are cleaned up before the\n";
  cout << "application exits:" << endl;
  return 0;
  }

Each call to singleton TaskMgr::instance() returns the
same TaskManager object pointer:
TaskManager object pointer = 0x40006148
TaskManager object pointer = 0x40006148
TaskManager object pointer = 0x40006148
TaskManager object pointer = 0x40006148
TaskManager object pointer = 0x40006148
TaskManager object pointer = 0x40006148
TakManager is running tasks
The singleton's resources are cleaned up before the
application exits:
TaskManager is getting the ax

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.