Singleton instance freeing - c++

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.

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.

What is the advantage of using shared_ptr with singleton

Here are two singletons, what does make the first one preferable, as both will instantiate only one instance of the corresponding class:
First:
class SharedPointerSingleton {
public:
static std::shared_ptr< SharedPointerSingleton> getSingleton(
{
if( s_pSingleton== 0 ) s_pSingleton = std::shared_ptr< SharedPointerSingleton>(new SharedPointerSingleton());
return s_pSingleton;
}
private:
SharedPointerSingleton(){};
static std::shared_ptr< SharedPointerSingleton> s_pSingleton;
};
Second:
class PointerSingleton {
public:
static PointerSingleton * getSingleton(
{
if( pSingleton== 0 ) pSingleton = new PointerSingleton ());
return pSingleton;
}
private:
PointerSingleton (){};
static PointerSingleton * pSingleton;
};
Both implementation have their pros and cons. First solution has overhead of using std::shared_ptr which could be noticeable in some situations. Second solution does not destroy singleton object at the end of program. Though memory would be released by OS at the end of program lifetime it is generally not a good practice not to properly destroy C++ objects. It may directly or indirectly release resources that are not cleaned by OS such as temporary files, shared memory etc and it is a common practice to deallocate resources in destructor.
The second leaks when the program ends (though the OS should clean up memory, your missing destructor calls might be a problem). That's probably why somebody added a smart pointer on top.
However, both versions are broken, being susceptible to initialization order problems.
Instead, the "proper" way to produce a singleton is like this:
class SharedPointerSingleton
{
SharedPointerSingleton() = default;
public:
static SharedPointerSingleton& getSingleton(
{
static SharedPointerSingleton instance;
return instance;
}
};
This is approach is safe and without the overhead of smart pointers or dynamic allocation. Now the object is constructed precisely when you first ask for it, which is far superior (unless you want it to happen before main … but then you can still instantiate it at namespace scope if you like by calling this function!).

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

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.