Aussie AI

Singleton Classes

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Singleton Classes

In a one-instance class there will only ever be one object defined from it. There are called “singletons” in the “design patterns” parlance. In this situation the class can be defined very efficiently by making use of compile-time initialization with data members declared as “static” members.

An example is a hash table implementation of a symbol table (e.g. in a compiler keyword table or an AI vocabulary table used by the tokenizer), where only one symbol table will ever be used. The crucial fragment from this code is:

    class SymbolTable {
      private:
        Node * table[TABLE_SIZE]; // Hash table - array of pointers
      public:
        SymbolTable(); // constructor
    };

    //-----------------------------------------------------------
    // Constructor - initialize the hash table to empty
    //-----------------------------------------------------------
    SymbolTable::SymbolTable()
    {
        for (int i = 0; i < TABLE_SIZE; i++) // all pointers are NULL
        table[i] = NULL;
    }

If there will only be one hash table, the constructor is needlessly inefficient. A more efficient version declares the hash table as a static data member and the implicit initialization to zero will set all the pointers to NULL at compile-time. The efficient code for a one-instance hash table is:

    class SymbolTable { // ONE INSTANCE ONLY
      private:
        static Node *table[TABLE_SIZE]; // Compile-time initialization
      public:
        SymbolTable() { } // constructor does nothing
    };

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++