Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Singleton example in C++
/*
* Example of a singleton design pattern.
* Copyright (C) 2011 Radek Pazdera
* 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();
};
/* Null, because instance will be initialized on demand. */
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if (instance == 0)
{
instance = new Singleton();
}
return 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;
}
@bit-rocket

This comment has been minimized.

Copy link

@bit-rocket bit-rocket commented May 4, 2017

If this is a header .h file, class implements should be written in .cpp file
Otherwise, compile error occurs.

@CMLDMR

This comment has been minimized.

Copy link

@CMLDMR CMLDMR commented Oct 4, 2017

Good Example to show singleton. Thank you.

@oliviazqq

This comment has been minimized.

Copy link

@oliviazqq oliviazqq commented Nov 22, 2017

thank you,very good

@Rushi-Kumar

This comment has been minimized.

Copy link

@Rushi-Kumar Rushi-Kumar commented Dec 1, 2017

how to implement in header only library.

@zhangxiao-ustc

This comment has been minimized.

Copy link

@zhangxiao-ustc zhangxiao-ustc commented Jan 23, 2018

Is this implementation thread-safe?

@BugLight

This comment has been minimized.

Copy link

@BugLight BugLight commented Feb 11, 2018

Your implementation has a memory leak.

@luca1337

This comment has been minimized.

Copy link

@luca1337 luca1337 commented Mar 10, 2018

nice example!

@xintongc

This comment has been minimized.

Copy link

@xintongc xintongc commented Mar 11, 2018

Very helpful! Thanks a lot!

@ZOulhadj

This comment has been minimized.

Copy link

@ZOulhadj ZOulhadj commented Mar 11, 2018

Nice, however, I just would say that there is a memory leak. When you create a raw pointer you need to make sure to delete it in the destructor. If not then make sure to new a smart pointer so it gets deleted automatically.

@OSinitsyn

This comment has been minimized.

Copy link

@OSinitsyn OSinitsyn commented Mar 24, 2018

The copy constructor and the copy assignment operator should be declared private, i.e.

private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);

Otherwise, you will be able to clone your object. If you are using C++ 11, you may leave the copy constructor and the copy assignment operator public but explicitly delete them:

public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

@ProgrammerXDesigner

This comment has been minimized.

Copy link

@ProgrammerXDesigner ProgrammerXDesigner commented May 11, 2018

Nice, but I have some notes here:

  • First, you have memory leak.
  • And second, you should declare the copy constructor and the assignment operator of your class as private or delete them explicitly to prevent cloning your object.
@akbarsaleemt

This comment has been minimized.

Copy link

@akbarsaleemt akbarsaleemt commented Jul 30, 2018

how can i access same object every time for my program
#include
using namespace std;
class student
{
private:
int id;
int marks;
public:
void adddata()
{
int i,mks;
cout<<"enter student marks and id:";
cin>>i;
cin>>mks;
id=i;
marks=mks;
print();
}
void print()
{
cout<<"student id num:"<<id<<endl;
cout<<"student marks:"<<marks<<endl;
}

};

int main()
{
student s;

s.adddata();

x.adddata();

return 0;

}

@mohamed-karaoui

This comment has been minimized.

Copy link

@mohamed-karaoui mohamed-karaoui commented Aug 23, 2018

The use of "static" inside the function getInstance() makes things even cleaner:

 * Example of a singleton design pattern.                                        
 * Copyright (C) 2011 Radek Pazdera                                              
 * 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:                                                                     
        /* Private constructor to prevent instancing. */                         
        Singleton();                                                             
                                                                                 
    public:                                                                      
        /* Static access method. */                                              
        static Singleton* getInstance();                                         
};                                                                               
                                                                                 
Singleton* Singleton::getInstance()                                              
{                                                                                
    static Singleton instance;                                                   
                                                                                 
    return &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;                                                 
}
@NateShaq

This comment has been minimized.

Copy link

@NateShaq NateShaq commented Apr 3, 2019

Singletons like this in multi-threaded environments. Worth a read.
https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf

@vikramojha89

This comment has been minimized.

Copy link

@vikramojha89 vikramojha89 commented Sep 9, 2019

If you delete constructor with Singleton()=delete; even your internal methods won't be able to call constructor

@Nidrax

This comment has been minimized.

Copy link

@Nidrax Nidrax commented Sep 22, 2019

Your implementation has a memory leak.

In what manner? Since their initialisation singletons are supposed to live as long as the application does, so you don't have to worry about that raw pointer as once the application execution ends, the application memory will be freed by the system anyway.

@metablaster

This comment has been minimized.

Copy link

@metablaster metablaster commented Oct 13, 2019

This is very bad example, first copy assignment and copy ctors should be deleted, also you fail to release memory.

@FFC12

This comment has been minimized.

Copy link

@FFC12 FFC12 commented Nov 22, 2019

This example is from 9 years ago. why you all people doing same critism again again like a parrot.When author write to this example , probably C++ 11 was not available.

@zjutjsj1004

This comment has been minimized.

Copy link

@zjutjsj1004 zjutjsj1004 commented Nov 29, 2019

Is this implementation thread-safe?

@fisherwise

This comment has been minimized.

Copy link

@fisherwise fisherwise commented Dec 3, 2019

This example is from 9 years ago. why you all people doing same critism again again like a parrot.When author write to this example , probably C++ 11 was not available.

for C++03 you should declare copy constructor and operator and not implement them to work around

@theIDinside

This comment has been minimized.

Copy link

@theIDinside theIDinside commented Jan 28, 2020

I see a bunch of people complain that memory is leaked. No it is not. The operating system will recover the memory (it essentially acts as a global variable).

@rakeshmalviya1985

This comment has been minimized.

Copy link

@rakeshmalviya1985 rakeshmalviya1985 commented May 7, 2020

Is this implementation thread-safe?

no i will make it

@rakeshmalviya1985

This comment has been minimized.

Copy link

@rakeshmalviya1985 rakeshmalviya1985 commented May 7, 2020

Is this implementation thread-safe?

no i will make it

@saravpreet14

This comment has been minimized.

Copy link

@saravpreet14 saravpreet14 commented Aug 6, 2020

This will make a new object. To prevent that you must delete copy constructor or make it private

Singleton a(*s);
std::cout << &a << std::endl;
@SwarajKetan

This comment has been minimized.

Copy link

@SwarajKetan SwarajKetan commented Oct 20, 2020

//I implement this way

class Singleton 
{
private:

    Singleton() { }
    void operator delete(void*) {}; // such that its not deleted accidentally
public:

    Singleton(Singleton&) = delete; // Copy prohibited
    void operator=(const Singleton&) = delete; // Assignment prohibited
    Singleton& operator=(Singleton&&) = delete; // Move assignment
    static Singleton* getInstance();
    // This is a sample method
    std::chrono::system_clock::time_point getTime() const {
        auto now = std::chrono::system_clock::now();
        return now;
    };
};

Singleton* Singleton::getInstance() {
    static Singleton* pInstance_;
    return pInstance_;
}

@philipphenkel

This comment has been minimized.

Copy link

@philipphenkel philipphenkel commented Oct 29, 2020

@SwarajKetan Your singleton gets never created. You could either add a new to your getInstance implementation or avoid pointers completely like here:

Singleton& Singleton::getInstance() {
    static Singleton instance;
    return instance;
}
@asdlei99

This comment has been minimized.

@TravisZhang

This comment has been minimized.

Copy link

@TravisZhang TravisZhang commented Jan 12, 2021

https://stackoverflow.com/questions/55490024/stdcall-once-when-should-it-be-used
I think you should use std::call_once to prevent multi-thread problems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment