Skip to content

src/singleton/Singleton.hpp

Classes

Name
class CSingleton

Attributes

Name
bool CSingleton< T >::isInitialized
T * CSingleton< T >::_instance

Defines

Name
SINGLETONINSTANCE(T)
SINGLETON(T)
SINGLETONCONSTRUCTOROVERRIDE(T)

Attributes Documentation

variable CSingleton< T >::isInitialized

bool CSingleton< T >::isInitialized = false;

variable CSingleton< T >::_instance

T * CSingleton< T >::_instance = NULL;

Macros Documentation

define SINGLETONINSTANCE

#define SINGLETONINSTANCE(
    T
)
CSingleton< T >::Instance()

define SINGLETON

#define SINGLETON(
    T
)
protected:                                      \
    friend class CSingleton< T >;               \
    T(T *) {}                                   \
    T(){}

define SINGLETONCONSTRUCTOROVERRIDE

#define SINGLETONCONSTRUCTOROVERRIDE(
    T
)
protected:                                      \
    friend class CSingleton< T >;               \
    T(T *) {}

Source code

//---------------------------------------------------------------------
// File:        Singleton.hpp
// Description: template for Singleton objects
// Created:     11/30/03
// Author:      Kenneth L. Hurley
//---------------------------------------------------------------------

#ifndef SINGLETON_H
#define SINGLETON_H

//
// this code is so that object can register themselves with
// the system.
//

template <class T>
class CSingleton 
{
private:
    static bool isInitialized;
    static T *_instance;                  // first initialize memory without constructor
public:
    static T *Instance()
    {
        // start lock for multithreading here
        if (_instance == NULL)
        {
            _instance = new T(_instance);
        }

        if (!isInitialized)
        {
            isInitialized = true;
            new (_instance) T();
        }
        return _instance;
    }; 

private: 
    CSingleton() {}; 
    ~CSingleton() {};
    // disable copy & assignment
    CSingleton( CSingleton const&);
    CSingleton& operator=( CSingleton const&);
};

template <class T>
bool CSingleton<T>::isInitialized = false;

template <class T>
T *CSingleton<T>::_instance = NULL;

#define SINGLETONINSTANCE(T)                        \
    CSingleton< T >::Instance()

#define SINGLETON(T)                                \
    protected:                                      \
        friend class CSingleton< T >;               \
        T(T *) {}                                   \
        T(){}

#define SINGLETONCONSTRUCTOROVERRIDE(T)             \
    protected:                                      \
        friend class CSingleton< T >;               \
        T(T *) {}


#endif  // #ifndef SINGLETON_H

Updated on 2026-03-04 at 13:10:45 -0800