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

Answer by ricab for How do you implement the Singleton design pattern?

$
0
0

Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).

A ConcreteSinleton can be implemented like this:

class ConcreteSingleton : public Singleton<ConcreteSingleton>{public:  ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)      : Singleton<StandardPaths>::Singleton{pass}  {}  // ... concrete interface  int f() const {return 42;}};

And then used with

ConcreteSingleton::instance().f();

Viewing all articles
Browse latest Browse all 25

Latest Images

Trending Articles



Latest Images

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