The following small example implements a singleton pattern that I've seen many times:
#include <iostream>
class SingletonTest {
private:
SingletonTest() {}
static SingletonTest *instance;
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest *get_instance() {
if(!instance) instance = new SingletonTest;
return instance;
}
};
SingletonTest *SingletonTest::instance = 0;
int main(int argc, char *argv[]) {
SingletonTest *s = SingletonTest::get_instance();
return 0;
}
The main problem I have with this is that the destructor of my singleton is never called.
I can instead make instance a (c++0x?) shared_ptr, which works well - except that it means my destructor has to be public.
I could add a static 'cleanup' method but that opens up the possibility of user error (i.e. forgetting to call it). It would also not allow for proper cleanup in the face of (unhandled) exceptions.
Is there a common strategy/pattern that will allow lazy instantiation, 'automatically' call my destructor, and still allow me to keep the destructor private?
...not exactly a direct answer, but too long for a comment - why not do the singleton this way:
class SingletonTest {
private:
SingletonTest() {}
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest& get_instance() {
static SingletonTest instance;
return instance;
}
};
Now you have a lazy singleton that will be destructed on exit... It's not any less re-entrant than your code...
You could write a deinitialization function and call atexit() inside the object constructor to register it. Then when C++ runtime deinitializes the module it will at some point after main() call your deinitialization function. That bold italic is there because you get rather loose control on when exactly it is called and that can lead to deinitialization order fiasco - be careful.
You could always friend the shared_ptr (or rather scoped_ptr, which is more fitting) to allow it access to your private destructor.
Note that there's also the system atexit() function which can register a function to call at the end of the application. You could pass a static function of your singleton that just does delete instanance; to it.
Note that it's usually a good idea separates the class that is to be a singleton from the singleton-ness of it. Especially for testing and/or when you do need the doubleton. :)
While I'm at it, try to avoid lazy initialization. Initialize/create your singletons at startup, in a well determined order. This allows them to shut down properly and resolves dependencies without surprises. (I have had cyclic singleton hell... it's easier than you think...)
You can use a private destructor with shared_ptr by passing in a deleter that has access to the destructor (such as a class defined as a member of SingletonTest).
However, you need to be very careful when destroying singletons to ensure that they are not used after they are destroyed. Why not just use a plain global variable anyway?
if you declare the class which does the actual delete op as a friend (let it be shared_ptr<SingletonTest> or some kind of default deleter) a friend, your destructor can be private.
Although i dont see any necessarity for making it private.
The first question is: do you want the singleton to be destructed.
Destructing a singleton can lead to order of destruction problems; and
since you're shutting down, the destructor can't be necessary to
maintain program invariants. About the only time you want to run the
destructor of a singleton is if it manages resources that the system
won't automatically clean up, like temporary files. Otherwise, it's
better policy to not call the destructor on it.
Given that, if you want the destructor to be called, there are two
alternatives: declare the single object as a static local variable in
the instance function, or use std::auto_ptr or something similar,
instead of a raw pointer, as the pointer to it.
Related
I have two managers (which are singletons):
A licenses manager, counting licences tokens when functionalities are used. The destructor of this release all the licences.
A Python manager, managing calls to Python from C++, it requires a specific license from the licences manager. The destructor calls the licences manager to finalize the license usage.
I suppose the order of destruction of the singleton is undefined. How can I avoid the mismatch at the destruction of the managers? Is it possible?
This is my typical implementation of a singleton:
class Manager : private boost::noncopyable
{
private:
struct singleton_deleter { void operator () (Manager* m) { delete m; } };
friend struct Manager::singleton_deleter;
private:
boost::mutex singleton_mutex;
boost::shared_ptr<Manager> singleton_instance;
public:
static Manager& instance()
{
if(!(bool)Manager::singleton_instance)
{
boost::mutex::scoped_lock lock(Manager::singleton_mutex);
if(!(bool)Manager::singleton_instance)
Manager::singleton_mutex.reset(new Manager, Manager::singleton_deleter());
}
return *Manager::singleton_instance;
}
private:
Manager() { this->lic = LicManager::instance().getLicense(); }
~Manager() { LicManager::instance().releaseLicense(this->lic); }
};
Note that since the destruction order of static objects in C++ is the reverse of their construction order, you can make the constructor of one singleton first construct the other singleton it depends on as a function-local static object. For example:
LicManager & LicManager::instance() {
static LicManager licenceManager;
return licenceManager;
}
Manager & Manager::instance() {
static Manager manager(LicManager::instance());
return manager;
}
Another way would be to use a shared_ptr to share ownership of the singleton, enforcing the destruction order. Make instance() return a shared_ptr instead of a reference. In your use case, store the return value of LicManager::instance() (e.g. a shared_ptr<LicManager>) in your Manager object. This forces LicManager to stay alive for the lifetime of Manager, even if the respective LicManager shared pointer in the global scope is destroyed.
Edit: As pointed out in the comments, yet another solution would be to have only one super singleton which owns all the others and controls the initialization/destruction order.
Store the singleton instance as a static local variable of the accessor function that returns a reference to it. In other words, use the Construct On First Use Idiom.
Then call the accessor function of singleton A, from the constructor of singleton B. This ensures that, the singleton A is constructed before B, which in turn ensures that A is destroyed after B.
There is a variation of this pattern which is to use - instead of a function local static object - a function local static raw pointer to a dynamic object, which is leaked on termination. That approach does not need the constructor of a singleton to call the accessor of another, but of course memory analysers will complain. The idea is that that the singleton is never destroyed, so you are free to depend on it in the destructors of other static objects.
Is it really a so restrictive pattern than you can not have two different classes implemented as singletons ??? If it's true, singleton looks like a useless pattern...
Singleton is a very restrictive pattern, and some might argue that it is useless. But it is not true that you couldn't have two different singleton classes.
i have this singleton pattern and it runs ok. But when i execute my program with valgrind to check memory leaks, it seems that the instance is never destroyed.
Where is my mistake?
Header
class Stopwords {
private:
static Stopwords* instance;
std::map<std::string,short> diccionario;
private:
Stopwords();
public:
~Stopwords();
public:
static Stopwords* getInstance();
std::map<std::string,short> getMap();
};
.cpp
Stopwords* Stopwords::instance = NULL;
Stopwords::Stopwords() {
diccionario = map<string,short>();
char nombre_archivo[] = "stopwords/stopwords.txt";
ifstream archivo;
archivo.open(nombre_archivo);
string stopword;
while(getline(archivo,stopword,',')) {
diccionario[stopword] = 1;
}
archivo.close();
}
Stopwords::~Stopwords() {
delete instance;
}
Stopwords* Stopwords::getInstance() {
if (instance == NULL) {
instance = new Stopwords ();
}
return instance;
}
map<string,short> Stopwords::getMap(){
return diccionario;
}
It's not relevant but in the initialization, i read a bunch of words from a file and i save them in a map instance.
Thanks
Stopwords::~Stopwords() {
delete instance;
}
This is the destructor for instances of the class. You probably intended this function to be called when the program ends, as though it were a kind of 'static' destructor, but that's not what this is.
So your destructor for instances of Stopwords initiates destruction of Stopwords instances; You've got an infinite loop here, which you never enter. If you do get into this loop then the program will probably just crash.
There's a simpler way to do singletons: Instead of keeping the instances as a static class member that you allocate manually, simply keep it as a static function variable. C++ will manage creating and destroying it for you.
class Stopwords {
public:
static Stopwords &getInstance() {
static Stopwords instance;
return instance;
}
~Stopwords();
std::map<std::string,short> getMap();
private:
Stopwords();
std::map<std::string,short> diccionario;
};
Also, you should mark member functions that don't need to modify the class as const:
std::map<std::string,short> getMap() const;
The problem is that you never call the destructor or delete on the instance pointer by hand, i.e. from outside the class. So the delete inside the destructor will never get executed, meaning the destructor will never get executed, meaning the delete will never get executed, meaning... You see what you did there? Your destructor is indirectly calling itself which will not go well. And you never call it from the outside, so it never gets called at all - luckily.
You should change your singleton implementation, maybe a Meyers singleton (look it up), or even better not use a singleton at all. In cases like this one, where they are data sources, there are just too much weaknesses of the pattern to deal with.
You allocate memory for instance with new. So the instance will be alive until delete is called.
Destructor is called in the case an instance of a class going to be killed.
Nothing kills (using delete) your instance, but destructor itself.
So the conclusion is that your instance is never killed.
Usually, when you use singleton you don't care to kill it before the program finishes. Why do you need this?
If you don't you better use static keyword to make explicit the fact that it is alive until the program finishes.
static Singleton& getInstance()
{
static Singleton s;
return s;
}
You can implement singleton in C++ by making the instance a function-static std::unique_ptr inside the instance getter, rather than a class-static variable. This ensures a call of destructor upon program's completion, and lets you create an instance that gets accessed polymorphically e.g. through a pointer to an abstract base class.
In your destructor you do:
Stopwords::~Stopwords() {
delete instance;
}
I would suggest you add:
Stopwords::~Stopwords() {
delete instance;
instance = 0;
}
This call makes sure that the pointer is not only removed from memory but points to nothing. When deleting a pointer you need to make sure it doesn't point to nothing anymore otherwise you may get memory leaks indeed.
Assuming this implementation of a singleton pattern ( of course we should avoid Singleton: it is just question), I have just been thinking about static object being created. It is created on heap by a new operator, sure, but how is this destroyed? In following example we have a leak, so how one should implement deletion of static singleton object? Should there be a please_delete() public interface adopted, so one can call myC->please_delete() or is there other way to achieve this?
class CC{
public:
static CC* cObj(){
if(c_ptr==NULL){
c_ptr=new CC();
return c_ptr;
}else return c_ptr;
}
int getValue(){return value_;}
void setValue(int val){value_=val;}
~CC(){cout<<"~CC";}
private:
CC():value_(12345){cout<<"CC";}
static CC* c_ptr;
int value_;
};
// Allocating and initializing CC's
// static data member. The pointer is being
// allocated - not the object itself.
CC *CC::c_ptr = 0;
int main(){
//Singleton pattern
CC* myC = CC::cObj();
cout<<myC->getValue();
return 0;
}
output: CC12345
RUN SUCCESSFUL (total time: 67ms)
I noticed that indeed we can always declare singleton static instance within shared_ptr as with boost::shared_ptr<CC> bCptr(CC::cObj()); but Singleton pattern doesn't mention the problem of deletion of the object at all so maybe there exists some other approach?
Part of the Singleton design pattern is that it is indestructible.
EDIT:
There are 2 varieties of singletons with respect to destructibility:
Destructible (They die when the application does)
Indestructible (They die when the machine does)
Either way, if built properly, once the singleton instance is created, it stays. This one of the major criticisms of the Singleton design pattern.
Here are a few references that address the destructibility aspect of the pattern.
http://nicolabonelli.wordpress.com/2009/06/04/singleton-a-mirage-of-perfection/
http://www10.informatik.uni-erlangen.de/Teaching/Courses/SS2009/CPP/altmann.pdf
http://sourcemaking.com/design_patterns/singleton
http://sourcemaking.com/design_patterns/to_kill_a_singleton
The classical singleton pattern does not describe the deletion aspect.
However, if I have to do it, I would start with a simple approach like the following (it is not fool-proof):
1) Similar to the static method for creating/retrieving the singleton object, say createObject(), there is a static method for destructing the singleton object, say destructObject()
2) There is a counter which counts the current number of objects in the system;
it starts at 0
on createObject() call, it increments by 1
on deleteObject() call, it decrements by 1.
If it reaches 0, then the delete is called to actually destruct the object
I prefer to not use a pointer.
class Single
{
private:
Single();
public:
Single& Instance()
{
static Single the_instance;
Return the_instance;
}
};
This singleton will live from the time Instance() is called until the application is exiting and performing the destruction of static objects. In this case the destructor of the singleton object will be called.
In practice, even when using a pointer as in the original example, the memory will be reclaimed by the OS upon application exit. However in this case the object's destructor will not be called.
In my project, I'm working with about 4 singletons made the Scott Meyer's way. One of them:
LevelRenderer& LevelRenderer::Instance()
{
static LevelRenderer obj;
return obj;
}
Now two of those Singletons, LevelRenderer and LevelSymbolTable interact with each other. For example, in this method:
void LevelRenderer::Parse(std::vector<std::string>& lineSet)
{
LevelSymbolTable& table = LevelSymbolTable::Instance();
/** removed code which was irrelevant **/
// for each line in lineSet
BOOST_FOREACH(std::string line, lineSet)
{
// for each character in the line
BOOST_FOREACH(char sym, line)
{
/** code... **/
// otherwise
else
{
sf::Sprite spr;
// Used LevelSymbolTable's Instance here...
table.GenerateSpriteFromSymbol(spr, sym);
// ^ Inside LevelRenderer
/** irrelevant code... **/
}
}
}
}
Now, although the problem hasn't occurred yet. The thing I am afraid of is, what if the LevelSymbolTable instance is already destroyed before I call GenerateSpriteFromSymbol ?
Since I used the Scott Meyer way, the Singleton's instance was allocated by the stack. Hence is is guaranteed to be destroyed using the last created first destroyed rule. Now if LevelSymbolTable's Instance is created after LevelRenderer's Instance, it will be destroyed before LevelRenderer's Instance, right? So then, if I call a method of LevelSymbolTable inside LevelRenderer (especially in LevelRenderer's destructor), I will be treading on undefined behaviour land.
As I said before, this problem hasn't actually occurred while debugging, and is purely my assumption and guess-work. So, is my conclusion correct? Is LevelSymbolTable liable to be destroyed before LevelRenderer. If so, is there any way out of this mess?
You don't have to worry about anything here.* The static keyword guarantees that it is available from when it is initialized to when the program exits. So, you can make a call to a static variable at any point after it has been initialized.
Also, you have a reference to LevelSymbolTable, not a local variable. This is what the ampersand after the class name means. So you can use it locally, but it's really "referring to" the true object which exists somewhere else. So, when the method exits, the reference will go out of scope but the object it refers to will not.
*Well, you may have to worry about one thing. In a destructor, you should just be cleaning up any memory or file references or other things of that nature you have a handle on. I don't know why you would be calling other objects in a destructor.
Define ownership relation between the objects. Either have LevelSymbolTable as member of LevelRenderer:
class LevelRenderer {
LevelSymbolTable symbolTable;
public:
static LevelRenderer& getInstance();
~LevelRenderer() { /* can use symbolTable here */ }
};
Or create one singleton Level that contains both SymbolTable and Renderer:
class Level {
SymbolTable symbolTable;
Renderer levelRenderer; // note the order here
public:
static Level& getInstance();
private:
/* have LeverRenderer save reference to symbol table,
now renderer can use symbol table anywhere */
Level() : levelRenderer(symbolTable)
{ /* ... */ }
};
EDIT: Or get rid of singletons alltogether. See why singletons are bad. I don't know the structure of your application, but from what I see, you could have Level as a normal class that knows how to render itself and has its symbol table. And have its lifetime connected to the level it is supposed to represent in the application.
Static instances will be created at the beginning of the program (before main) and cleaned up at the end (after main), and you can't rely on any particular order in which they are cleaned up. That is, if you have two instances (let's just make them globals for the sake of simplicity)
class one {
one() {}
~one() {}
};
class two {
two() {}
~two() {}
};
one the_one;
two the_other;
int main() {
...
return 0;
}
You cannot and should not make assumptions about the_one being active in the constructor or destructor of the_other. (And vice versa.)
You can, however, rely on them both being active in any other member function, and within main itself.
The scenario you raise in your question is unlikely to occur, because Parse is probably being called while the program is still active. Only when the program is about to exit would destructors be called.
In you comments, you indicate a slightly different worry, which is global destructor interdependency. This might actually occur if you have global objects that register themselves with some global container. You might expect that objects would remove themselves from the container, and that the container would eject objects.
One way to deal with this is to allow the container to take ownership of the objects that register with it. This means that what gets registered with the global container are dynamically allocated instances, rather than your Scott Meyer's singleton instances. Then, the global container would take charge of cleaning up the registered items when its global destructor is called.
I have such singleton structure:
// Hpp
class Root : public boost::noncopyable
{
public:
~Root();
static Root &Get();
void Initialize();
void Deinitialize();
private:
Root(); // Private for singleton purposes
static Root *mInstance;
Manager1 *mManager1;
Manager2 *mManager2;
};
// Cpp
Root *Root::mInstance = nullptr;
Root::Root()
{
mInstance = this;
// Managers are using `mInstance` in their constructors
mManager1 = new Manager1();
mManager2 = new Manager2();
mInstance->Initialize();
}
Root::~Root() { delete mManager1; delete mManager2; }
Root &Root::Get()
{
if (mInstance == nullptr) mInstance = new Root();
return *mInstance;
}
void Root::Deinitialize()
{
delete mInstance;
}
And here is the usage of this singleton:
Root::Get();
// Some code calling related to mManager1 and mManager2
Root::Get().Deinitialize();
The questions are:
This is memory safely to use such singleton structure?
How can I automate deletion of mInstance (call dtor manually). Because the user could forget to call Deinitialize() method.
For a single-threaded application where the singleton isn't accessed after exiting main() you can use a fairly simple approach which does everything automatically:
Root& Root::get() {
static std::unique_ptr<Root> rc(new Root());
return *rc;
}
The static in this context means that the variable is initialized the first time the function is called and then stays put. The C++ run-time arranges for the static variable rc to be destroyed at some point. For multi-threaded appplications where threads are started before entering main() you need a different approach which makes sure that the static variable is initialized only by on thread.
That said, please note that I strongly recommend not to employ the anti-pattern Singleton (also known as Global Data). The above code sample doesn't constitute a recommendation of any sort! There are few valid uses where you want to use a singleton, most uses are not. All valid uses I have seen use an immutable Singleton. Mutable singleton objects tend to become a synchronization point and tend to obfuscate the use data as global data does.
If you aren't using Visual Studio or C++11, you won't have a unique_ptr<>. In that case, you should stick with boost::scoped_ptr.hpp, since std::auto_ptr will soon be completely deprecated.
#include <boost/scoped_ptr.hpp>
#include <iostream>
class Foo {
Foo() { std::cout << "constructor" << std::endl; }
public:
static Foo& Get() {
static boost::scoped_ptr<Foo> ptr(new Foo);
return *ptr;
}
~Foo() { std::cout << "destructor" << std::endl; }
};
int main() {
Foo& f = Foo::Get();
// f is now valid until the program exits.
//Then it is destroyed before the program finishes exiting.
std::cout << "Work here" << std::endl;
}
Or you can write your own simplified scoped_ptr.
template<typename _T>
class scoped_ptr {
_T* const mPtr;
public:
scoped_ptr(_T* const t) : mPtr(t) {}
~scoped_ptr() { delete mPtr; }
operator _T* () { return const_cast<_T*>(mPtr); }
// add more operators like -> if you want them
};
Have you considered what would happened if your singleton wasn't deleted at all?
By definition, a singleton is an single object shared by many client objects as the clients tend to come and go. Most of the time your singleton will live as long as your process.
When your process shuts down, OS will reclaim most resources (memory, file handles, sockets...) and it is perfectly normal to allocate that singleton and then just let it die. This would be my recommendation.
The code is simpler. Less function calls, less complexity. No need to consider when terminate should be called and that's what brought you here.
With explicit cleanup, as your application becomes more complex (and they tend to as you keep adding features), you introduce the risk that some other object will attempt to access singleton reference after it was terminated and destroyed. Now instead of harmless memory leak which gets wiped up by the OS immediately, you have an ugly unhandled exception dialog that your users get to look at.
It is also a good practice to put Initialize() function for the singleton inside GetInstance() (as pdillon3 demonstrated) instead of having your application explicitly call Initialize(). You didn't specify this part, and if your project is an executable, you should be ok with existing design. But just be careful if you put this code inside a DLL. Some people assume DllMain is a good place to initialize singleton objects and it's not. During DllMain, loader lock global critical section is locked and singleton initializations tend to cause all kinds of trouble.
Plus now instead of 3 methods in your singleton interface, you are down to just one: GetInstance(), nice and simple.
Lastly, as Dietmar mentioned (although I still consider Singleton to be a pattern, not an anti-pattern and GoF agree with me), you should really consider whether or not you actually need a singleton. I use them from time to time, but only when I have no choice, not because they are convenient. They really are a design pattern of last resort when alternative is even more evil. Don't use them just because they are convenient.