Search⌘ K
AI Features

Singleton Pattern Implementation

Explore the Singleton pattern implementation in C++ by examining two practical examples. Understand the role of private constructors, static instance variables, and how to prevent copying. Learn Meyers' approach for thread-safe single instance creation and verify singleton behavior through output comparisons.

Example one: simple implementation

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

C++
#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 ...