Crafting a Singleton Class in C++: A Tale of Singular Elegance

Ahoy, fellow coders! Today, let’s embark on a thrilling journey into the realm of singleton classes in C++. If you’re not familiar with the term, fear not! A singleton class is like that one legendary sword in a game—you can only wield one of its kind at a time. In other words, it ensures there’s only ever one instance of a class floating around in your code.

The Singleton Quest Begins…

Picture this: you’re building a mighty castle of code, and you stumble upon a need for a class that must exist in a single, glorious instance. That’s where the singleton pattern comes into play!

Step 1: Raise the Drawbridge with a Private Constructor

In the land of singletons, the first rule is simple yet crucial: make the constructor private! This prevents any mischievous outsider from creating instances of your class willy-nilly.

1
2
3
4
5
class Singleton {
private:
Singleton() {} // Private constructor to prevent instantiation
// Additional implementation goes here...
};

Method 1: Meyers’ Singleton - The Heroic Approach

Now, let’s dive into the magical realm of static member functions. Behold, the power of static! With this enchanting keyword, we can summon a single instance of our class.

1
2
3
4
5
6
7
8
9
class Singleton {
private:
Singleton() {} // Private constructor to prevent instantiation
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
};

Here’s how it works: whenever you call getInstance(), it conjures up a static instance if one doesn’t already exist. Otherwise, it simply returns the existing instance, ensuring there’s only one to rule them all! Meyers’ Singleton leverages the mystical properties of static local variables, ensuring that the instance is forged with utmost care and thread safety.

Method 2: The Static Pointer to Glory

But wait, our adventure isn’t over yet! There’s one more method to explore: the static pointer approach. Brace yourselves as we delve deeper into the arcane arts of C++!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Singleton {
private:
Singleton() {} // Private constructor to prevent instantiation
static Singleton* instancePtr; // Static pointer to the instance

public:
static Singleton* getInstance() {
if (!instancePtr) {
instancePtr = new Singleton();
}
return instancePtr;
}
};

Singleton* Singleton::instancePtr = nullptr; // Initializing the static pointer

This method employs a static pointer to the singleton instance, ensuring lazy initialization and a journey free of unnecessary overhead.

Final Step : Complete Code

Copy the below code in a .cpp file and compile the code below using

g++ -s ./c++/cpp_codes/singleton.cpp -o singleton.out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<bits/stdc++.h>

using namespace std;

class Singleton {
private:
Singleton() {} // Private constructor to prevent instantiation
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
void print(){
cout << "hello world" << endl;
}
};



int main(){
Singleton obj = Singleton::getInstance();
obj.print();
return 0;
}

Special Keyword and

In C++, the static keyword has special significance when applied to member variables and functions:

  • Static Member Variables: When a member variable is declared as static, it means there is only one instance of that variable shared among all instances of the class.
  • Static Member Functions: A static member function is a function that belongs to the class rather than instances of the class. It can be called without an object of the class.

Steps to Implement a Singleton Class:

  • Private Constructor: Ensure that the class has a private constructor to prevent external instantiation.
  • Static Member Function/Object: Provide a static member function or object that returns a reference to the singleton instance.
  • Lazy Initialization: The singleton instance should be created on-demand to conserve resources.
  • Thread Safety (Optional): If the singleton will be accessed by multiple threads, ensure thread safety during initialization. Meyers’ Singleton automatically handles thread safety.

Epilogue: The Singleton Legacy Lives On

And there you have it, intrepid adventurers! By mastering the arcane arts of singleton classes, you’ve unlocked the secrets of controlling class instantiation like a true coding wizard. Whether you choose the static sorcery, the mystical member object, Meyers’ elegance, or the static pointer to glory, remember to wield your singleton powers responsibly in your coding quests!

Author

Himanshu Upreti

Posted on

2024-03-01

Updated on

2024-03-07

Licensed under

Comments