can any one here give me idea about singleton class?? thanks in advance for your valuable suggestion. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

can any one here give me idea about singleton class?? thanks in advance for your valuable suggestion.

2nd Sep 2016, 4:25 PM
Shivesh Karan Mehta
Shivesh Karan Mehta - avatar
3 Answers
+ 4
#include <stdexcept> class Singleton { protected: static bool alreadyCreated; public: Singleton() { if (alreadyCreated) { throw logic_error("Can't create more than one Singleton object."); } alreadyCreated = true; } ~Singleton() { alreadyCreated = false; } }; Singleton::alreadyCreated = false; Then make your class inherit from Singleton and add exception handling when trying to instanciate.
2nd Sep 2016, 4:57 PM
Zen
Zen - avatar
+ 1
Hi Zen, your code is nice. Still, you can copy and assign the class you created as the copy constructor and the assignment operator are automatically generated by the compiler. The Singleton pattern for C++03 (this is what SoloLearn C++ uses) is to make the all constructors (if no constructor is defined, an automatically generated default constructor is defined) private, as well as the assignment operator and provide a static method that returns the only acceptable instance. Nevertheless, in C++11 and above the pattern is to delete the default constructor and the assignment operator. In addition, the Singleton pattern has rightfully been critized for either being really hard to implement or just deceptive as the a single instance of a class can only be ensured for one process. Start the program in multiple times in parallel and you don't have that secured anymore (problem in distributed systems and pretty much every system is distributed).
2nd Sep 2016, 7:37 PM
Stefan
Stefan - avatar
- 1
can you please explain this what this properly do??
2nd Sep 2016, 5:11 PM
Shivesh Karan Mehta
Shivesh Karan Mehta - avatar