Its not thread-safe and leaks memorysomething like this:Try again
![]()
Its not thread-safe and leaks memorysomething like this:Try again
![]()
Ehhm ...
Yes, you have to destroy the global object when program terminates. But it was just an idea, an example of singleton. You can build it with static member etc.
If you want it thread safe, use semaphores or eny else method.
But idea of singleton is good, in any case it more useful then you comment
Cheers
Ok, ok I knowAnyway, here is a paper on Singleton and Double-Checked Locking, by Meyers and Alexandrescu http://www.aristeia.com/Papers/DDJ_J...04_revised.pdf.
I think its good to be aware of the problems with singletons.
Ok sorry guys end of off-topic.
You can also protect singleton creation by using fetch-and-add semantics (e.g. with QAtomicInt) or simply by creating the singleton instance manually in the main thread so that instance() always returns an existing object and never tries to create one (just like QCoreApplication does). Another viable approach is to use a wait condition so that many threads at once can execute instance() but still just one can create the singleton instance.
And all singleton problems can be neatly avoided by creating the shared object explicitly and passing it to all objects that need it
It can be constructed before any of the threads are, can be deleted after all of them have finished, creation can take arguments, ...
Not even talking about making unittest easier since each test can have a clean instance instead of using the same instance over and over again.
Cheers,
_
Bookmarks