...

/

Singleton Pattern Implementation

Singleton Pattern Implementation

Learn about the singleton pattern through coding examples.

Example one: simple implementation

Here’s an example of the singleton pattern implementation in C++.

Press + to interact
#include <iostream>
class MySingleton{
private:
static MySingleton* instance;
MySingleton()= default;
~MySingleton()= default;
public:
MySingleton(const MySingleton&)= delete;
MySingleton& operator=(const MySingleton&)= delete;
static MySingleton* getInstance(){
if ( !instance ){
instance= new MySingleton();
}
return instance;
}
};
MySingleton* MySingleton::instance= nullptr;
int main(){
std::cout << '\n';
std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
std::cout << "MySingleton::getInstance(): "<< MySingleton::getInstance() << '\n';
std::cout << '\n';
}

Code explanation

  • Line 3: We created the MySingleton class.

  • Lines 5–8: We declared a private static MySingleton, which will store the object of the class alongside a private constructor and destructor.

  • Lines 11–12: We deleted the copy constructor and assignment operator so that our instance can’t be copied. ...