Quantcast
Channel: How do you implement the Singleton design pattern? - Stack Overflow
Viewing all articles
Browse latest Browse all 25

Answer by T.E.D. for How do you implement the Singleton design pattern?

$
0
0

It is indeed probably allocated from the heap, but without the sources there is no way of knowing.

The typical implementation (taken from some code I have in emacs already) would be:

Singleton * Singleton::getInstance() {    if (!instance) {        instance = new Singleton();    };    return instance;};

...and rely on the program going out of scope to clean up afterwards.

If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.

Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.


Viewing all articles
Browse latest Browse all 25

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>