Skip to content

Instantly share code, notes, and snippets.

@uzername
Forked from pazdera/gist:1098119
Last active February 28, 2019 10:51
Show Gist options
  • Save uzername/76a0f6fdb8f592d6dd3f8210f23e4903 to your computer and use it in GitHub Desktop.
Save uzername/76a0f6fdb8f592d6dd3f8210f23e4903 to your computer and use it in GitHub Desktop.
Singleton example in C++
/*
* Example of a singleton design pattern.
* Copyright (C) 2011 Radek Pazdera
* 2018, uzername. No memory leak; assignment and copy operators are hidden from public access.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
class Singleton
{
private:
/* Here will be the instance stored. */
static Singleton* instance;
/* Private constructor to prevent instancing. */
Singleton();
public:
/* Static access method. */
static Singleton* getInstance();
/* you should declare the copy constructor and the assignment operator of your class as private or delete them explicitly to prevent cloning your object. */
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
/* to be the most accurate, remove instance */
static void afterUsageOfSingleton();
};
/* Null, because instance will be initialized on demand. */
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if (instance == 0)
{
instance = new Singleton();
}
return instance;
}
void Singleton::afterUsageOfSingleton()
{
delete instance;
}
Singleton::Singleton()
{}
int main()
{
//new Singleton(); // Won't work
Singleton* s = Singleton::getInstance(); // Ok
Singleton* r = Singleton::getInstance();
/* The addresses will be the same. */
std::cout << s << std::endl;
std::cout << r << std::endl;
Singleton::afterUsageOfSingleton();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment