It happens so that I have a need of the infamous singleton pattern. Better yet, it happens so that I have a need of infamous C++ templates in combination with that pattern. So, what troubles me is this:
template <class T>
class PDatabaseTable
{
...
static PDatabaseTable <T> & instance()
{
static PDatabaseTable <T> singleton;
return singleton;
}
...
};
This is a typical way to implement a singleton that's supposed to be created on the first use. Now, here we have a static variable singleton. Since the instance() function may be called from several different modules, the question is: will there be only one instance of the object for any given type T, or will every module instantiate its very own singleton?
There will only be one instance for each type T
, just as, if it weren't a template, there would only be one instance.
The function is inline, meaning that although it can be defined in multiple compilation units, after linking there will be only one version of it, and only one instance of any local static objects.
Your singleton is called Meyers Singleton and you can find an explanation about thread safety of this singleton type in Static locals and threadsafety in g++ article which nicely explains how static local variables are thread-safe to create.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With