how to delete singleton object - c++

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.

Related

Can a singleton use another one in its destructor?

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.

Singleton pattern destructor C++

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.

Memory managed C++ singletons

I'm programming a game engine right now. The hardest part for me has been the memory management. I've been putting in as many optimizations as possible (because every frame counts, right?) and realized that the best way to approach this would be to do resource management using Stack and Pool allocators. The problem is, I can't figure out how to make a singleton class that is memory managed by these allocators.
My singletons are managers, so they are actually rather big, and memory management of them is important for the start up speed of my game. I basically want to be able to call my allocators' alloc() functions, which return type void*, and create my singleton in this allocated space.
I've been thinking about putting a static boolean called instantiated in each singleton class and having the constructor return NULL if instantiated is true. Would this work?
This is why everybody thinks Singletons suck. They suck horrifically. This is but one aspect of their suck, which will suck down your whole application with it.
In order to solve your problem: Do not use Suckletons.
Ok so I will answer this by sharing my own experience. Normally I want a class to have all its own functionality and later realize ok this might need a factory method to supply other code with an instance of my object that is singular. The instance really should only be defined once to maintain state etc. Therefore this is what I do for classes that don't have all of their initialization wrapped into construction. I don't want to clutter my existing class with singletonsuxness so I create a factory wrapper class to help me with this. You could use Myer's singleton pattern which is elegant and encapsulates the locking by letting the implementation of the static local variable (relies on compiler implementation of static local init which is not always a good idea) handle the locking but the problem comes if you, like me, want your objects default constructed so that you can use STL vectors etc on them easily and later call some type of initialization on them, possibly passing parameters to this method, to make them heavier.
class X
{
public:
bool isInitialized () { return _isInitialized; } ; // or some method like
// establishCxn to have it
// bootstrapped
void initialize();
X() {} // constructor default, not initialized, light weight object
private:
bool _isInitialzied;
};
// set initialization to false
X::X(): _isInitialized(false) {}
void X::intialize()
{
if (isInitiazlied()) { return; }
.... init code ....
_isInitialized = true
}
// now we go ahead and put a factory wrapper on top of this to help manage the
// singletoness nature. This could be templatized but we don't as we want the
// flexibility to override our own getinstance to call a specific initialize for the
// object it is holding
class XFactory
{
public:
static X* getInstance();
private:
static boost::mutex _lock;
// light weight static object of yourself ( early instantiation ) to put on the stack
// to avoid thread issues, static method member thread saftey, and DCLP pattern
// threading races that can stem from compiling re-ordering of items
static XFactory _instance;
// making this pointer volatile so that the compiler knows not to reorder our
// instructions for it ( depends on compiler implementation but it is a safe guard )
X* volatile _Xitem;
X* getXitem () { return _Xitem; }
void createInstance();
void doCleanUp();
// stop instantiation or unwanted copies
XClientFactory();
~XClientFactory();
XClientFactory(XClientFactory const&);
XClientFactory& operator=(XClientFactory const&);
};
// on construction we create and set the pointer to a new light weight version of the
// object we are interested in construction
XFactory::XFactory() : _Xitem( new X; )
{
}
// note our factory method is returning a pointer to X not itself (XFactory)
X* XFactory::getInstance()
{
// DCLP pattern, first thread might have initialized X while others
// were waiting for the lock in this way your double check locking is
// on initializing the X container in the factory and not the factory object itself.
// Worst case your initialization could happen more than once but it should check the
// boolean before it starts (see initialization method above) and sets the boolean at
// the end of it. Also your init should be such that a re-initialization will not put
// the object in a bad state. The most important thing to note is that we
// moved the double check locking to the contained object's initialization method
// instead of the factory object
if (! XFactory::_instance.getXitem()->isInitialized() )
{
boost::unique_lock<boost::mutex> guard(XFactory::_lock);
if (! XFactory::_instance.getXitem()->isInitialized() )
{
XFactory::_instance.getXitem()->initialize();
}
}
return XFactory::_instance.getXitem();
}
// XFactory private static instance on the stack will get cleaned up and we need to
// call the delete on the pointer we created for the _Xitem
XFactory::~XFactory()
{
doCleanUp();
}
XFactory::doCleanUp()
{
delete _Xitem; //
}
That's it, let me know what you think. I also wrestled recently with singleton and all the pit falls. Also, we are not using a 0x compiler yet that would ensure that the Myers singleton will be implemented in a thread safe way just using a local static variable

Singleton instance freeing

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.

Managing a singleton destructor

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.