Reputation:
I'm looking at two implementations of the Singleton design pattern.
I wanted to know how the second one works, in particular:
Why has the author chosen to return DB as a reference.
Why does the static class object DB in getDatabaseConnection() not need to be defined outside of the SingleDatabase class as such:
SingletonDatabase& SingletonDatabase::DB;
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!
Upvotes: 0
Views: 72
Reputation: 8437
To complete @Scheff's points:
I'm used to seeing the implementation with a static pointer, which the author mentioned is not thread safe. He prefers this method.
As this Q/A shows, implementing the singleton pattern with pointers is not thread-safe.
Upvotes: 0
Reputation: 20151
- Why has the author chosen to return DB as a reference.
Instead of a reference, a pointer could have been used as well. The reference expresses better that the pointee is granted to exist. (Return by value instead would have corrupted the concept.)
- Why does the static class object DB in getDatabaseConnection() not need to be defined outside of the SingleDatabase class as such:
SingletonDatabase& SingletonDatabase::DB;
It's not a member variable but a static
variable with a local scope but the life-time of a static → granted to exist from first access until end of process.
SO: What is the lifetime of a static variable in a C++ function? (a little bit aged but still correct)
This would've been worked the same way in a plain function. That the surrounding function is a (static
member function) is not that relevant concerning this.
- Does a static class object, like a static variable, only get created once (and is shared amongst all objects of the same class)?
Yes.
To be correct, it's shared between any caller of this function.
Btw. this is known as Meyers Singleton:
FleCSI: Meyer’s Singleton → SO: C++ Singleton design pattern
SO: Is Meyers' implementation of the Singleton pattern thread safe?
Upvotes: 2