C ++: templates and singleton template

It happens that I need the infamous singleton picture. Even better, it happens that I need the infamous C ++ templates in combination with this template. So what bothers me is:

template <class T> class PDatabaseTable { ... static PDatabaseTable <T> & instance() { static PDatabaseTable <T> singleton; return singleton; } ... }; 

This is a typical singleton implementation that should be created upon first use. Now we have a static singleton variable. Since the instance () function can be called from several different modules, the question arises: will there be only one instance of the object for any given type T , or will each module create its own singleton?

+7
source share
4 answers

For each type T will be only one instance, just as if it were not a template, there would be only one instance.

The function is built-in, which means that although it can be defined in several compilation units, after linking there will be only one version of it and only one instance of any local static objects.

+5
source

Your singleton is called Meyers Singleton, and you can find an explanation of the thread safety of this singleton type in Static local and threading provisionings in g ++ , which perfectly explains how static local variables create threads.

+2
source

There will definitely be only one instance .

I am just wondering why you cannot transfer this static object from a function to the class body?

 template <class T> class PDatabaseTable { static PDatabaseTable <T> singleton; static PDatabaseTable <T> & instance() { return singleton; } }; template<class T> PDatabaseTable<T> PDatabaseTable<T>::singleton; 
+1
source

You can move the init of a static element outside the body of the class, and this is also possible for a static function.

 template <typename T> class Singleton { public: static Singleton<T>* Singleton::getInstance(); T* getMember() { member_; } protected: Singleton() { member_ = new T; } ~Singleton() { if (singleton_) delete member_; } private: static Singleton<T>* singleton_; T* member_; }; template <typename T> Singleton<T>* Singleton<T>::getInstance() { if (NULL == singleton_) singleton_ = new Singleton; return singleton_; } template <typename T> Singleton<T>* Singleton<T>::singleton_ = NULL; 
+1
source

All Articles