Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
It has no dynamic memory allocation.
Being a Singleton, you usually do not want it to be destructed.
It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.
#Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Cătălin's answer is automatically thread-safe in current C++, but will be in C++0x.
I did not find a CRTP implementation among the answers, so here it is:
template<typename HeirT>
class Singleton
{
public:
Singleton() = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static HeirT &instance()
{
static HeirT instance;
return instance;
}
};
To use just inherit your class from this, like: class Test : public Singleton<Test>
We went over this topic recently in my EECS class. If you want to look at the lecture notes in detail, visit http://umich.edu/~eecs381/lecture/IdiomsDesPattsCreational.pdf. These notes (and quotations I give in this answer) were created by my Professor, David Kieras.
There are two ways that I know to create a Singleton class correctly.
First Way:
Implement it similar to the way you have it in your example. As for destruction, "Singletons usually endure for the length of the program run; most OSs will recover memory and most other resources when a program terminates, so there is an argument for not worrying about this."
However, it is good practice to clean up at program termination. Therefore, you can do this with an auxiliary static SingletonDestructor class and declare that as a friend in your Singleton.
class Singleton {
public:
static Singleton* get_instance();
// disable copy/move -- this is a Singleton
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
friend class Singleton_destroyer;
private:
Singleton(); // no one else can create one
~Singleton(); // prevent accidental deletion
static Singleton* ptr;
};
// auxiliary static object for destroying the memory of Singleton
class Singleton_destroyer {
public:
~Singleton_destroyer { delete Singleton::ptr; }
};
// somewhere in code (Singleton.cpp is probably the best place)
// create a global static Singleton_destroyer object
Singleton_destoyer the_destroyer;
The Singleton_destroyer will be created on program startup, and "when program terminates, all global/static objects are destroyed by the runtime library shutdown code (inserted by the linker), so the_destroyer will be destroyed; its destructor will delete the Singleton, running its destructor."
Second Way
This is called the Meyers Singleton, created by C++ wizard Scott Meyers. Simply define get_instance() differently. Now you can also get rid of the pointer member variable.
// public member function
static Singleton& Singleton::get_instance()
{
static Singleton s;
return s;
}
This is neat because the value returned is by reference and you can use . syntax instead of -> to access member variables.
"Compiler automatically builds code that creates 's' first time through the
declaration, not thereafter, and then deletes the static object at program
termination."
Note also that with the Meyers Singleton you "can get into very difficult situation if objects rely on each other at the time of
termination - when does the Singleton disappear relative to other objects? But for simple applications, this works fine."
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main() function. There may be problems really, when some dependent objects are allocated inside main.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication was allocated on stack in the main function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init() and term() methods for all the singletons and call them inside main. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance() or not.
Has anyone mentioned std::call_once and std::once_flag?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.
If you want to allocate the object in heap, why don't use a unique pointer. Memory will also be deallocated since we are using a unique pointer.
class S
{
public:
static S& getInstance()
{
if( m_s.get() == 0 )
{
m_s.reset( new S() );
}
return *m_s;
}
private:
static std::unique_ptr<S> m_s;
S();
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
std::unique_ptr<S> S::m_s(0);
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...
struct Store{
std::array<Something, 1024> data;
size_t get(size_t idx){ /* ... */ }
void incr_ref(size_t idx){ /* ... */}
void decr_ref(size_t idx){ /* ... */}
};
template<Store* store_p>
struct ItemRef{
size_t idx;
auto get(){ return store_p->get(idx); };
ItemRef() { store_p->incr_ref(idx); };
~ItemRef() { store_p->decr_ref(idx); };
};
Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances
Now somewhere inside a function (such as main) you can do:
auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201);
The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).
If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:
template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning
instances of ItemRef<Store_t, store_p>. */ };
The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
It restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
class Singleton {
private:
int data;
static Singleton* instance;
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
this->data = 0;
cout << "constructor called.." << endl;
}
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
return instance;
}
}
int main() {
Singleton *s = s->getInstance();
Singleton *s1 =s1->getInstance();
}
This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper:
http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf
My implementation is similar to Galik's. The difference is my implementation allows the shared pointers to clean up allocated memory, as opposed to holding onto the memory until the application is exited and the static pointers are cleaned up.
#pragma once
#include <memory>
template<typename T>
class Singleton
{
private:
static std::weak_ptr<T> _singleton;
public:
static std::shared_ptr<T> singleton()
{
std::shared_ptr<T> singleton = _singleton.lock();
if (!singleton)
{
singleton.reset(new T());
_singleton = singleton;
}
return singleton;
}
};
template<typename T>
std::weak_ptr<T> Singleton<T>::_singleton;
Your code is correct, except that you didn't declare the instance pointer outside the class. The inside class declarations of static variables are not considered declarations in C++, however this is allowed in other languages like C# or Java etc.
class Singleton
{
public:
static Singleton* getInstance( );
private:
Singleton( );
static Singleton* instance;
};
Singleton* Singleton::instance; //we need to declare outside because static variables are global
You must know that Singleton instance doesn't need to be manually deleted by us. We need a single object of it throughout the whole program, so at the end of program execution, it will be automatically deallocated.
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
Add minor improvements to make it unit-test friendly.
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.
Simple singleton class, This must be your header class file
#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H
class SingletonClass
{
public:
static SingletonClass* Instance()
{
static SingletonClass* instance = new SingletonClass();
return instance;
}
void Relocate(int X, int Y, int Z);
private:
SingletonClass();
~SingletonClass();
};
#define sSingletonClass SingletonClass::Instance()
#endif
Access your singleton like this:
sSingletonClass->Relocate(1, 2, 5);
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);
Related
I work in a project where Singletons are usually implemented like this:
class Singleton
{
public:
static Singleton& get();
virtual ~Singleton() = default;
// Used for unit tests
static void reset();
protected:
static std::unique_ptr<Singleton>& instance();
};
unique_ptr<Singleton>& Singleton::instance()
{
static unique_ptr<Singleton> instance;
return instance;
}
Singleton& Singleton::get()
{
auto& instance = instance();
if (!instance) {
// We cannot use make_unique<T>() as constructor is private
instance = unique_ptr<Singleton>(new Singleton());
}
return *instance;
}
void Singleton::reset() { instance().reset(); }
// Private constructor
Singleton::Singleton() {}
No thread safety is required here.
Is there any advantages of using a static unique_ptr ?
What are the consequences of creating the Singleton with unique_ptr<T>(new T()) ?
Since our Singletons can carry (some) global state, a public reset() was implemented for testing purposes, is it the only way and can this be improved ?
I have found some examples of C++ singleton design patterns here.
But never implemented with unique_ptr like mine.
There are exists two ways to reset Meyer's singleton:
#include <new>
class Singleton
{
public:
static Singleton& instance() {
static Singleton instance;
return instance;
}
virtual ~Singleton() = default;
// Option 1 - easy and convinient if Singleton is copyable or movable
void reset1() {
*this = {};
}
// Option 2 - works always
void reset2() {
this->~Singleton();
new (this) Singleton;
}
private:
Singleton() {}
};
2nd option is basically doing exactly what you are doing with releasing/creating std::unique_ptr, except without deallocation/allocation of storage.
You'd get lazy instance creation if you use a pointer as opposed to a reference.
If the reset() is a logical reset, you won't need a pointer, a reference would do but, if the requirement is that of a memory reset, you'll need it.
Since the lifetime of the static singleton instance is the whole application lifetime, you don't need to care about the RAII benefit that you get with unique ptr.
But, you'd use unique_ptr to indicate exclusive ownership over the resource and some guidelines forbid using raw pointers for non-owning
The current code allows copying and moving of your instance, breaking the Singleton invariances.
There is no need to use std::unique_ptr. Use references
class Singleton
{
public:
static Singleton& instance();
virtual ~Singleton() = default;
// Used for unit tests
void reset();
private:
Singleton();
int stuff;
};
Singleton& Singleton::instance()
{
static Singleton instance;
return instance;
}
void Singleton::reset() { stuff = 0; }
// Private constructor
Singleton::Singleton() {}
Note that this design is dominated by your requirement for a reset function. This prevents you from using certain Singleton implementations, like e.g. Meyer's Singleton.
In general you would want a singleton implementation to not allow the implementation of a reset method, because now your singleton is not really a singleton anymore. But it might of course make sense to "water down" the singleton for testing purposes.
If multithreading-safety is not a concern, your singleton implementation is overly complicated and could be reduced to:
class Singleton
{
public:
static Singleton& get() {
if (!mInstance) {
mInstance = std::unique_ptr<Singleton>(new Singleton());
}
return *mInstance;
}
static void reset() { mInstance.reset(); }
private:
static inline std::unique_ptr<Singleton> mInstance{};
};
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
It has no dynamic memory allocation.
Being a Singleton, you usually do not want it to be destructed.
It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.
#Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Cătălin's answer is automatically thread-safe in current C++, but will be in C++0x.
I did not find a CRTP implementation among the answers, so here it is:
template<typename HeirT>
class Singleton
{
public:
Singleton() = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static HeirT &instance()
{
static HeirT instance;
return instance;
}
};
To use just inherit your class from this, like: class Test : public Singleton<Test>
We went over this topic recently in my EECS class. If you want to look at the lecture notes in detail, visit http://umich.edu/~eecs381/lecture/IdiomsDesPattsCreational.pdf. These notes (and quotations I give in this answer) were created by my Professor, David Kieras.
There are two ways that I know to create a Singleton class correctly.
First Way:
Implement it similar to the way you have it in your example. As for destruction, "Singletons usually endure for the length of the program run; most OSs will recover memory and most other resources when a program terminates, so there is an argument for not worrying about this."
However, it is good practice to clean up at program termination. Therefore, you can do this with an auxiliary static SingletonDestructor class and declare that as a friend in your Singleton.
class Singleton {
public:
static Singleton* get_instance();
// disable copy/move -- this is a Singleton
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
friend class Singleton_destroyer;
private:
Singleton(); // no one else can create one
~Singleton(); // prevent accidental deletion
static Singleton* ptr;
};
// auxiliary static object for destroying the memory of Singleton
class Singleton_destroyer {
public:
~Singleton_destroyer { delete Singleton::ptr; }
};
// somewhere in code (Singleton.cpp is probably the best place)
// create a global static Singleton_destroyer object
Singleton_destoyer the_destroyer;
The Singleton_destroyer will be created on program startup, and "when program terminates, all global/static objects are destroyed by the runtime library shutdown code (inserted by the linker), so the_destroyer will be destroyed; its destructor will delete the Singleton, running its destructor."
Second Way
This is called the Meyers Singleton, created by C++ wizard Scott Meyers. Simply define get_instance() differently. Now you can also get rid of the pointer member variable.
// public member function
static Singleton& Singleton::get_instance()
{
static Singleton s;
return s;
}
This is neat because the value returned is by reference and you can use . syntax instead of -> to access member variables.
"Compiler automatically builds code that creates 's' first time through the
declaration, not thereafter, and then deletes the static object at program
termination."
Note also that with the Meyers Singleton you "can get into very difficult situation if objects rely on each other at the time of
termination - when does the Singleton disappear relative to other objects? But for simple applications, this works fine."
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main() function. There may be problems really, when some dependent objects are allocated inside main.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication was allocated on stack in the main function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init() and term() methods for all the singletons and call them inside main. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance() or not.
Has anyone mentioned std::call_once and std::once_flag?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.
If you want to allocate the object in heap, why don't use a unique pointer. Memory will also be deallocated since we are using a unique pointer.
class S
{
public:
static S& getInstance()
{
if( m_s.get() == 0 )
{
m_s.reset( new S() );
}
return *m_s;
}
private:
static std::unique_ptr<S> m_s;
S();
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
std::unique_ptr<S> S::m_s(0);
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...
struct Store{
std::array<Something, 1024> data;
size_t get(size_t idx){ /* ... */ }
void incr_ref(size_t idx){ /* ... */}
void decr_ref(size_t idx){ /* ... */}
};
template<Store* store_p>
struct ItemRef{
size_t idx;
auto get(){ return store_p->get(idx); };
ItemRef() { store_p->incr_ref(idx); };
~ItemRef() { store_p->decr_ref(idx); };
};
Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances
Now somewhere inside a function (such as main) you can do:
auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201);
The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).
If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:
template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning
instances of ItemRef<Store_t, store_p>. */ };
The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
It restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
class Singleton {
private:
int data;
static Singleton* instance;
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
this->data = 0;
cout << "constructor called.." << endl;
}
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
return instance;
}
}
int main() {
Singleton *s = s->getInstance();
Singleton *s1 =s1->getInstance();
}
This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper:
http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf
My implementation is similar to Galik's. The difference is my implementation allows the shared pointers to clean up allocated memory, as opposed to holding onto the memory until the application is exited and the static pointers are cleaned up.
#pragma once
#include <memory>
template<typename T>
class Singleton
{
private:
static std::weak_ptr<T> _singleton;
public:
static std::shared_ptr<T> singleton()
{
std::shared_ptr<T> singleton = _singleton.lock();
if (!singleton)
{
singleton.reset(new T());
_singleton = singleton;
}
return singleton;
}
};
template<typename T>
std::weak_ptr<T> Singleton<T>::_singleton;
Your code is correct, except that you didn't declare the instance pointer outside the class. The inside class declarations of static variables are not considered declarations in C++, however this is allowed in other languages like C# or Java etc.
class Singleton
{
public:
static Singleton* getInstance( );
private:
Singleton( );
static Singleton* instance;
};
Singleton* Singleton::instance; //we need to declare outside because static variables are global
You must know that Singleton instance doesn't need to be manually deleted by us. We need a single object of it throughout the whole program, so at the end of program execution, it will be automatically deallocated.
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
Add minor improvements to make it unit-test friendly.
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.
Simple singleton class, This must be your header class file
#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H
class SingletonClass
{
public:
static SingletonClass* Instance()
{
static SingletonClass* instance = new SingletonClass();
return instance;
}
void Relocate(int X, int Y, int Z);
private:
SingletonClass();
~SingletonClass();
};
#define sSingletonClass SingletonClass::Instance()
#endif
Access your singleton like this:
sSingletonClass->Relocate(1, 2, 5);
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
It has no dynamic memory allocation.
Being a Singleton, you usually do not want it to be destructed.
It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.
#Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Cătălin's answer is automatically thread-safe in current C++, but will be in C++0x.
I did not find a CRTP implementation among the answers, so here it is:
template<typename HeirT>
class Singleton
{
public:
Singleton() = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static HeirT &instance()
{
static HeirT instance;
return instance;
}
};
To use just inherit your class from this, like: class Test : public Singleton<Test>
We went over this topic recently in my EECS class. If you want to look at the lecture notes in detail, visit http://umich.edu/~eecs381/lecture/IdiomsDesPattsCreational.pdf. These notes (and quotations I give in this answer) were created by my Professor, David Kieras.
There are two ways that I know to create a Singleton class correctly.
First Way:
Implement it similar to the way you have it in your example. As for destruction, "Singletons usually endure for the length of the program run; most OSs will recover memory and most other resources when a program terminates, so there is an argument for not worrying about this."
However, it is good practice to clean up at program termination. Therefore, you can do this with an auxiliary static SingletonDestructor class and declare that as a friend in your Singleton.
class Singleton {
public:
static Singleton* get_instance();
// disable copy/move -- this is a Singleton
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
friend class Singleton_destroyer;
private:
Singleton(); // no one else can create one
~Singleton(); // prevent accidental deletion
static Singleton* ptr;
};
// auxiliary static object for destroying the memory of Singleton
class Singleton_destroyer {
public:
~Singleton_destroyer { delete Singleton::ptr; }
};
// somewhere in code (Singleton.cpp is probably the best place)
// create a global static Singleton_destroyer object
Singleton_destoyer the_destroyer;
The Singleton_destroyer will be created on program startup, and "when program terminates, all global/static objects are destroyed by the runtime library shutdown code (inserted by the linker), so the_destroyer will be destroyed; its destructor will delete the Singleton, running its destructor."
Second Way
This is called the Meyers Singleton, created by C++ wizard Scott Meyers. Simply define get_instance() differently. Now you can also get rid of the pointer member variable.
// public member function
static Singleton& Singleton::get_instance()
{
static Singleton s;
return s;
}
This is neat because the value returned is by reference and you can use . syntax instead of -> to access member variables.
"Compiler automatically builds code that creates 's' first time through the
declaration, not thereafter, and then deletes the static object at program
termination."
Note also that with the Meyers Singleton you "can get into very difficult situation if objects rely on each other at the time of
termination - when does the Singleton disappear relative to other objects? But for simple applications, this works fine."
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main() function. There may be problems really, when some dependent objects are allocated inside main.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication was allocated on stack in the main function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init() and term() methods for all the singletons and call them inside main. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance() or not.
Has anyone mentioned std::call_once and std::once_flag?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.
If you want to allocate the object in heap, why don't use a unique pointer. Memory will also be deallocated since we are using a unique pointer.
class S
{
public:
static S& getInstance()
{
if( m_s.get() == 0 )
{
m_s.reset( new S() );
}
return *m_s;
}
private:
static std::unique_ptr<S> m_s;
S();
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
std::unique_ptr<S> S::m_s(0);
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...
struct Store{
std::array<Something, 1024> data;
size_t get(size_t idx){ /* ... */ }
void incr_ref(size_t idx){ /* ... */}
void decr_ref(size_t idx){ /* ... */}
};
template<Store* store_p>
struct ItemRef{
size_t idx;
auto get(){ return store_p->get(idx); };
ItemRef() { store_p->incr_ref(idx); };
~ItemRef() { store_p->decr_ref(idx); };
};
Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances
Now somewhere inside a function (such as main) you can do:
auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201);
The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).
If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:
template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning
instances of ItemRef<Store_t, store_p>. */ };
The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
It restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
class Singleton {
private:
int data;
static Singleton* instance;
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
this->data = 0;
cout << "constructor called.." << endl;
}
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
return instance;
}
}
int main() {
Singleton *s = s->getInstance();
Singleton *s1 =s1->getInstance();
}
This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper:
http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf
My implementation is similar to Galik's. The difference is my implementation allows the shared pointers to clean up allocated memory, as opposed to holding onto the memory until the application is exited and the static pointers are cleaned up.
#pragma once
#include <memory>
template<typename T>
class Singleton
{
private:
static std::weak_ptr<T> _singleton;
public:
static std::shared_ptr<T> singleton()
{
std::shared_ptr<T> singleton = _singleton.lock();
if (!singleton)
{
singleton.reset(new T());
_singleton = singleton;
}
return singleton;
}
};
template<typename T>
std::weak_ptr<T> Singleton<T>::_singleton;
Your code is correct, except that you didn't declare the instance pointer outside the class. The inside class declarations of static variables are not considered declarations in C++, however this is allowed in other languages like C# or Java etc.
class Singleton
{
public:
static Singleton* getInstance( );
private:
Singleton( );
static Singleton* instance;
};
Singleton* Singleton::instance; //we need to declare outside because static variables are global
You must know that Singleton instance doesn't need to be manually deleted by us. We need a single object of it throughout the whole program, so at the end of program execution, it will be automatically deallocated.
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
Add minor improvements to make it unit-test friendly.
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.
Simple singleton class, This must be your header class file
#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H
class SingletonClass
{
public:
static SingletonClass* Instance()
{
static SingletonClass* instance = new SingletonClass();
return instance;
}
void Relocate(int X, int Y, int Z);
private:
SingletonClass();
~SingletonClass();
};
#define sSingletonClass SingletonClass::Instance()
#endif
Access your singleton like this:
sSingletonClass->Relocate(1, 2, 5);
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
It has no dynamic memory allocation.
Being a Singleton, you usually do not want it to be destructed.
It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.
#Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Cătălin's answer is automatically thread-safe in current C++, but will be in C++0x.
I did not find a CRTP implementation among the answers, so here it is:
template<typename HeirT>
class Singleton
{
public:
Singleton() = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static HeirT &instance()
{
static HeirT instance;
return instance;
}
};
To use just inherit your class from this, like: class Test : public Singleton<Test>
We went over this topic recently in my EECS class. If you want to look at the lecture notes in detail, visit http://umich.edu/~eecs381/lecture/IdiomsDesPattsCreational.pdf. These notes (and quotations I give in this answer) were created by my Professor, David Kieras.
There are two ways that I know to create a Singleton class correctly.
First Way:
Implement it similar to the way you have it in your example. As for destruction, "Singletons usually endure for the length of the program run; most OSs will recover memory and most other resources when a program terminates, so there is an argument for not worrying about this."
However, it is good practice to clean up at program termination. Therefore, you can do this with an auxiliary static SingletonDestructor class and declare that as a friend in your Singleton.
class Singleton {
public:
static Singleton* get_instance();
// disable copy/move -- this is a Singleton
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
friend class Singleton_destroyer;
private:
Singleton(); // no one else can create one
~Singleton(); // prevent accidental deletion
static Singleton* ptr;
};
// auxiliary static object for destroying the memory of Singleton
class Singleton_destroyer {
public:
~Singleton_destroyer { delete Singleton::ptr; }
};
// somewhere in code (Singleton.cpp is probably the best place)
// create a global static Singleton_destroyer object
Singleton_destoyer the_destroyer;
The Singleton_destroyer will be created on program startup, and "when program terminates, all global/static objects are destroyed by the runtime library shutdown code (inserted by the linker), so the_destroyer will be destroyed; its destructor will delete the Singleton, running its destructor."
Second Way
This is called the Meyers Singleton, created by C++ wizard Scott Meyers. Simply define get_instance() differently. Now you can also get rid of the pointer member variable.
// public member function
static Singleton& Singleton::get_instance()
{
static Singleton s;
return s;
}
This is neat because the value returned is by reference and you can use . syntax instead of -> to access member variables.
"Compiler automatically builds code that creates 's' first time through the
declaration, not thereafter, and then deletes the static object at program
termination."
Note also that with the Meyers Singleton you "can get into very difficult situation if objects rely on each other at the time of
termination - when does the Singleton disappear relative to other objects? But for simple applications, this works fine."
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main() function. There may be problems really, when some dependent objects are allocated inside main.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication was allocated on stack in the main function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init() and term() methods for all the singletons and call them inside main. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance() or not.
Has anyone mentioned std::call_once and std::once_flag?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.
If you want to allocate the object in heap, why don't use a unique pointer. Memory will also be deallocated since we are using a unique pointer.
class S
{
public:
static S& getInstance()
{
if( m_s.get() == 0 )
{
m_s.reset( new S() );
}
return *m_s;
}
private:
static std::unique_ptr<S> m_s;
S();
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
std::unique_ptr<S> S::m_s(0);
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...
struct Store{
std::array<Something, 1024> data;
size_t get(size_t idx){ /* ... */ }
void incr_ref(size_t idx){ /* ... */}
void decr_ref(size_t idx){ /* ... */}
};
template<Store* store_p>
struct ItemRef{
size_t idx;
auto get(){ return store_p->get(idx); };
ItemRef() { store_p->incr_ref(idx); };
~ItemRef() { store_p->decr_ref(idx); };
};
Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances
Now somewhere inside a function (such as main) you can do:
auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201);
The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).
If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:
template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning
instances of ItemRef<Store_t, store_p>. */ };
The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
It restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
class Singleton {
private:
int data;
static Singleton* instance;
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
this->data = 0;
cout << "constructor called.." << endl;
}
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
return instance;
}
}
int main() {
Singleton *s = s->getInstance();
Singleton *s1 =s1->getInstance();
}
This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper:
http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf
My implementation is similar to Galik's. The difference is my implementation allows the shared pointers to clean up allocated memory, as opposed to holding onto the memory until the application is exited and the static pointers are cleaned up.
#pragma once
#include <memory>
template<typename T>
class Singleton
{
private:
static std::weak_ptr<T> _singleton;
public:
static std::shared_ptr<T> singleton()
{
std::shared_ptr<T> singleton = _singleton.lock();
if (!singleton)
{
singleton.reset(new T());
_singleton = singleton;
}
return singleton;
}
};
template<typename T>
std::weak_ptr<T> Singleton<T>::_singleton;
Your code is correct, except that you didn't declare the instance pointer outside the class. The inside class declarations of static variables are not considered declarations in C++, however this is allowed in other languages like C# or Java etc.
class Singleton
{
public:
static Singleton* getInstance( );
private:
Singleton( );
static Singleton* instance;
};
Singleton* Singleton::instance; //we need to declare outside because static variables are global
You must know that Singleton instance doesn't need to be manually deleted by us. We need a single object of it throughout the whole program, so at the end of program execution, it will be automatically deallocated.
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
Add minor improvements to make it unit-test friendly.
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.
Simple singleton class, This must be your header class file
#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H
class SingletonClass
{
public:
static SingletonClass* Instance()
{
static SingletonClass* instance = new SingletonClass();
return instance;
}
void Relocate(int X, int Y, int Z);
private:
SingletonClass();
~SingletonClass();
};
#define sSingletonClass SingletonClass::Instance()
#endif
Access your singleton like this:
sSingletonClass->Relocate(1, 2, 5);
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way?
In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
Can any one provide me a sample of Singleton in c++?
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
Singleton: How should it be used
See this two article about initialization order and how to cope:
Static variables initialisation order
Finding C++ static initialization order problems
See this article describing lifetimes:
What is the lifetime of a static variable in a C++ function?
See this article that discusses some threading implications to singletons:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
See this article that explains why double checked locking will not work on C++:
What are all the common undefined behaviours that a C++ programmer should know about?
Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
It has no dynamic memory allocation.
Being a Singleton, you usually do not want it to be destructed.
It will get torn down and deallocated when the program terminates, which is the normal, desired behavior for a singleton. If you want to be able to explicitly clean it, it's fairly easy to add a static method to the class that allows you to restore it to a clean state, and have it reallocate next time it's used, but that's outside of the scope of a "classic" singleton.
#Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()
using
template <class X>
X& singleton()
{
static X x;
return x;
}
Neither this nor Cătălin's answer is automatically thread-safe in current C++, but will be in C++0x.
I did not find a CRTP implementation among the answers, so here it is:
template<typename HeirT>
class Singleton
{
public:
Singleton() = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
static HeirT &instance()
{
static HeirT instance;
return instance;
}
};
To use just inherit your class from this, like: class Test : public Singleton<Test>
We went over this topic recently in my EECS class. If you want to look at the lecture notes in detail, visit http://umich.edu/~eecs381/lecture/IdiomsDesPattsCreational.pdf. These notes (and quotations I give in this answer) were created by my Professor, David Kieras.
There are two ways that I know to create a Singleton class correctly.
First Way:
Implement it similar to the way you have it in your example. As for destruction, "Singletons usually endure for the length of the program run; most OSs will recover memory and most other resources when a program terminates, so there is an argument for not worrying about this."
However, it is good practice to clean up at program termination. Therefore, you can do this with an auxiliary static SingletonDestructor class and declare that as a friend in your Singleton.
class Singleton {
public:
static Singleton* get_instance();
// disable copy/move -- this is a Singleton
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
friend class Singleton_destroyer;
private:
Singleton(); // no one else can create one
~Singleton(); // prevent accidental deletion
static Singleton* ptr;
};
// auxiliary static object for destroying the memory of Singleton
class Singleton_destroyer {
public:
~Singleton_destroyer { delete Singleton::ptr; }
};
// somewhere in code (Singleton.cpp is probably the best place)
// create a global static Singleton_destroyer object
Singleton_destoyer the_destroyer;
The Singleton_destroyer will be created on program startup, and "when program terminates, all global/static objects are destroyed by the runtime library shutdown code (inserted by the linker), so the_destroyer will be destroyed; its destructor will delete the Singleton, running its destructor."
Second Way
This is called the Meyers Singleton, created by C++ wizard Scott Meyers. Simply define get_instance() differently. Now you can also get rid of the pointer member variable.
// public member function
static Singleton& Singleton::get_instance()
{
static Singleton s;
return s;
}
This is neat because the value returned is by reference and you can use . syntax instead of -> to access member variables.
"Compiler automatically builds code that creates 's' first time through the
declaration, not thereafter, and then deletes the static object at program
termination."
Note also that with the Meyers Singleton you "can get into very difficult situation if objects rely on each other at the time of
termination - when does the Singleton disappear relative to other objects? But for simple applications, this works fine."
Here is an easy implementation.
#include <Windows.h>
#include <iostream>
using namespace std;
class SingletonClass {
public:
static SingletonClass* getInstance() {
return (!m_instanceSingleton) ?
m_instanceSingleton = new SingletonClass :
m_instanceSingleton;
}
private:
// private constructor and destructor
SingletonClass() { cout << "SingletonClass instance created!\n"; }
~SingletonClass() {}
// private copy constructor and assignment operator
SingletonClass(const SingletonClass&);
SingletonClass& operator=(const SingletonClass&);
static SingletonClass *m_instanceSingleton;
};
SingletonClass* SingletonClass::m_instanceSingleton = nullptr;
int main(int argc, const char * argv[]) {
SingletonClass *singleton;
singleton = singleton->getInstance();
cout << singleton << endl;
// Another object gets the reference of the first object!
SingletonClass *anotherSingleton;
anotherSingleton = anotherSingleton->getInstance();
cout << anotherSingleton << endl;
Sleep(5000);
return 0;
}
Only one object created and this object reference is returned each and every time afterwords.
SingletonClass instance created!
00915CB8
00915CB8
Here 00915CB8 is the memory location of singleton Object, same for the duration of the program but (normally!) different each time the program is run.
N.B. This is not a thread safe one.You have to ensure thread safety.
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main() function. There may be problems really, when some dependent objects are allocated inside main.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication was allocated on stack in the main function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init() and term() methods for all the singletons and call them inside main. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance() or not.
Has anyone mentioned std::call_once and std::once_flag?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.
If you want to allocate the object in heap, why don't use a unique pointer. Memory will also be deallocated since we are using a unique pointer.
class S
{
public:
static S& getInstance()
{
if( m_s.get() == 0 )
{
m_s.reset( new S() );
}
return *m_s;
}
private:
static std::unique_ptr<S> m_s;
S();
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
std::unique_ptr<S> S::m_s(0);
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper:
http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf
In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...
struct Store{
std::array<Something, 1024> data;
size_t get(size_t idx){ /* ... */ }
void incr_ref(size_t idx){ /* ... */}
void decr_ref(size_t idx){ /* ... */}
};
template<Store* store_p>
struct ItemRef{
size_t idx;
auto get(){ return store_p->get(idx); };
ItemRef() { store_p->incr_ref(idx); };
~ItemRef() { store_p->decr_ref(idx); };
};
Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances
Now somewhere inside a function (such as main) you can do:
auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201);
The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).
If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:
template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning
instances of ItemRef<Store_t, store_p>. */ };
The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
Add minor improvements to make it unit-test friendly.
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
It restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
class Singleton {
private:
int data;
static Singleton* instance;
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
this->data = 0;
cout << "constructor called.." << endl;
}
Singleton* Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
return instance;
}
}
int main() {
Singleton *s = s->getInstance();
Singleton *s1 =s1->getInstance();
}
My implementation is similar to Galik's. The difference is my implementation allows the shared pointers to clean up allocated memory, as opposed to holding onto the memory until the application is exited and the static pointers are cleaned up.
#pragma once
#include <memory>
template<typename T>
class Singleton
{
private:
static std::weak_ptr<T> _singleton;
public:
static std::shared_ptr<T> singleton()
{
std::shared_ptr<T> singleton = _singleton.lock();
if (!singleton)
{
singleton.reset(new T());
_singleton = singleton;
}
return singleton;
}
};
template<typename T>
std::weak_ptr<T> Singleton<T>::_singleton;
Your code is correct, except that you didn't declare the instance pointer outside the class. The inside class declarations of static variables are not considered declarations in C++, however this is allowed in other languages like C# or Java etc.
class Singleton
{
public:
static Singleton* getInstance( );
private:
Singleton( );
static Singleton* instance;
};
Singleton* Singleton::instance; //we need to declare outside because static variables are global
You must know that Singleton instance doesn't need to be manually deleted by us. We need a single object of it throughout the whole program, so at the end of program execution, it will be automatically deallocated.
The paper that was linked to above describes the shortcoming of double checked locking is that the compiler may allocate the memory for the object and set a pointer to the address of the allocated memory, before the object's constructor has been called. It is quite easy in c++ however to use allocaters to allocate the memory manually, and then use a construct call to initialize the memory. Using this appraoch, the double-checked locking works just fine.
Simple singleton class, This must be your header class file
#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H
class SingletonClass
{
public:
static SingletonClass* Instance()
{
static SingletonClass* instance = new SingletonClass();
return instance;
}
void Relocate(int X, int Y, int Z);
private:
SingletonClass();
~SingletonClass();
};
#define sSingletonClass SingletonClass::Instance()
#endif
Access your singleton like this:
sSingletonClass->Relocate(1, 2, 5);
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);