jeudi 17 octobre 2019

Static Objects in a Class (Singleton)

I'm looking at two implementations of the Singleton design pattern.

I wanted to know how the second one works, in particular:

  1. Why has the author chosen to return DB as a reference.

  2. Why does the static class object DB in getDatabaseConnection() not need to be defined outside of the SingleDatabase class as such:

SingletonDatabase& SingletonDatabase::DB;
  1. Does a static class object, like a static variable, only get created once (and is shared amongst all objects of the same class)?

Implementation

class SingletonDatabase {
    private:
        SingletonDatabase() {
            std::cout << "Initializing database" << std::endl;
            instanceCount++; // Used in testing later on.
        }

    public:
        SingletonDatabase(const SingletonDatabase&) = delete;
        SingletonDatabase& operator=(const SingletonDatabase&) = delete;
        static SingletonDatabase& getDatabaseConnection() {
            static SingletonDatabase DB;
            return DB;
        }
        static int instanceCount;
};

int SingletonDatabase::instanceCount = 0;

I'm used to seeing the implementation with a static pointer, which the author mentioned is not thread safe. He prefers this method.

Thanks!

Aucun commentaire:

Enregistrer un commentaire