Re: static template member
Michael D. Carney wrote:
In article <1151026564.153900.130230@r2g2000cwb.googlegroups.com>,
The program is missing the definition of foo's static
variable, the_instance. Whether foo is a class template or
not, foo::the_instance still has to be defined somewhere. It
is not.
So adding the missing definition after foo's declaration,
fixes the problem:
template <class T>
foo<T> foo<T>::the_instance;
Be careful with that in VC8, however. If you link together a
program that consists of several dlls, and the template is
referenced in more than one of the dlls, each dll that
references the template will have its own instance of the
static member of the template. In linux (or any non-windows OS
that I'm aware of), the instance will only exist once in the
program, and each library will reference the same instance
(which, I think, is the way its supposed to work according to
the standard).
According to the standard, as soon as you use dynamic linking,
you have undefined behavior. An implementation can do whatever
it wants. I'm not too familiar with Windows, but I know that
under Solaris, you can get both behaviors, depending on what you
want. (Most of the time, of course, you want to isolate the
dynamiclyl linked objects as much as possible; the fact that one
dynamically linked object happens to use some particular
global variable in its implementation shouldn't interfere with
any other dynamically linked object which might accidentally use
a global object of the same type.)
The upshot of this is that if you're using the foo template
above to implement a generic singleton, you won't get a
singleton (i.e. one instance per process), but rather you'll
get one instance per dll, which is definitely not what you
want.
It depends, but I would say that most of the time, it is
definitly what you want. The fact that my plugin happens to use
some particular singleton (with a particular name) shouldn't
interfere with other plugins, even if they accidentally use the
same name.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]