Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Templates and the singleton pattern

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?

like image 628
Septagram Avatar asked Apr 21 '11 04:04

Septagram


2 Answers

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.

like image 82
Mike Seymour Avatar answered Sep 30 '22 02:09

Mike Seymour


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.

like image 34
O.C. Avatar answered Sep 30 '22 00:09

O.C.