Can a singleton use another one in its destructor? - c++

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.

Related

How to create a singleton object using std::unique_ptr of a class with private destructor? [duplicate]

I've created all singletons in my program with that document in mind:
http://erdani.com/publications/DDJ_Jul_Aug_2004_revised.pdf
(in case anyone wondered why singleton, all of them are factories and some of them store some global settings concerning how they should create instances).
Each of them looks somehow like this:
declaration:
class SingletonAndFactory {
static SingletonAndFactory* volatile instance;
public:
static SingletonAndFactory& getInstance();
private:
SingletonAndFactory();
SingletonAndFactory(
const SingletonAndFactory& ingletonFactory
);
~SingletonAndFactory();
};
definition:
boost::mutex singletonAndFactoryMutex;
////////////////////////////////////////////////////////////////////////////////
// class SingletonAndFactory {
SingletonAndFactory* volatile singletonAndFactory::instance = 0;
// public:
SingletonAndFactory& SingletonAndFactory::getInstance() {
// Singleton implemented according to:
// "C++ and the Perils of Double-Checked Locking".
if (!instance) {
boost::mutex::scoped_lock lock(SingletonAndFactoryMutex);
if (!instance) {
SingletonAndFactory* volatile tmp = (SingletonAndFactory*) malloc(sizeof(SingletonAndFactory));
new (tmp) SingletonAndFactory; // placement new
instance = tmp;
}
}
return *instance;
}
// private:
SingletonAndFactory::SingletonAndFactory() {}
// };
Putting aside question what design of singleton is the best (since it would start a pointless flame war) my question is: would it benefit me to replace normal pointer with std::unique_ptr? In particular, would it call singleton's destructor on program exit? If so how would I achieve it? When I tried to add something like friend class std::unique_ptr<SingletonAndFactory>; it didn't worked out since compiler keep on complaining that the destructor is private.
I know it doesn't matter in my current project since none of factories have something that would require cleaning of any sort, but for future reference I would like to know how to implement such behavior.
It's not the unique_ptr itself that does the deletion, it's the deleter. So if you wanted to go with the friend approach, you'd have to do this:
friend std::unique_ptr<SingletonFactory>::deleter_type;
However, I don't think it's guaranteed that the default deleter will not delegate the actual delete to another function, which would break this.
Instead, you might want to supply your own deleter, perhaps like this:
class SingletonFactory {
static std::unique_ptr<SingletonFactory, void (*)(SingletonFactory*)> volatile instance;
public:
static SingletonFactory& getInstance();
private:
SingletonFactory();
SingletonFactory(
const SingletonFactory& ingletonFactory
);
~SingletonFactory();
void deleter(SingletonFactory *d) { d->~SingletonFactory(); free(d); }
};
And in the creation function:
SingletonFactory* volatile tmp = (SingletonFactory*) malloc(sizeof(SingletonFactory));
new (tmp) SingletonFactory; // placement new
instance = decltype(instance)(tmp, &deleter);
In C++11, you can guarantee thread-safe lazy initialisation and destruction at the end of the program using a local static:
SingletonAndFactory& SingletonAndFactory::getInstance() {
static SingletonAndFactory instance;
return instance;
}
Beware that this can still cause lifetime issues, as it may be destroyed before other static objects. If they try to access it from their destructors, then you'll be in trouble.
Before that, it was impossible (although the above was guaranteed by many compilers). As described in the document you link to, volatile has nothing to do with thread synchronisation, so your code has a data race and undefined behaviour. Options are:
Take the (potentially large) performance hit of locking to check the pointer
Use whatever non-portable atomic intrinsics your compiler provides to test the pointer
Forget about thread-safe initialisation, and make sure it's initialised before you start your threads
Don't use singletons
I favour the last option, since it solves all the other problems introduced by the Singleton anti-pattern.

how to delete singleton object

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.

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

How to ensure Singleton is not destroyed prematurely?

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.

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.