This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: PCH, and more generally C++ parser performance


>     >> template <class T> struct S { static int i; };
>     >> 
>     >> template <class T> int S<T>::i = f();
>     >> 
>     >> inline void g () { S<int>.i = 7; }
>     >> 
>     >> This program requires you to instantiate `S<int>::i', even if
>     >> you don't need `g'.
> 
>     Zack> I don't understand C++ well enough to know why.  In fact, I
>     Zack> can't parse
> 
>     Zack> template <class T> int S<T>::i = f();
> 
> Oh.  That's called a "static data member".  Think of it as a global
> variable, but inside a class scope.  There's only one such thing
> (that's why it's global) -- as opposed to a field, or ordinary data
> member, of which there is one per object.

Hm.  Is int S<T>::i the same variable as the static int i inside the
declaration of struct S?  If so then I think I get it: this expression
provides the initializer for that variable.  But it still might not be
used, because we haven't said what T is yet.

> The point is that the instantiation -- in the body of G -- causes this
> static data member to come in to existence, and I believe the standard
> requires that we call `f'.  (Which of course might have side-effects.)

And here's where I'd expect as-if to come into play.  If the only
references to S<int>::i are in g and the S<T>::i = f() expression, and
g is never used, can the program tell if S<int>::i does not actually
exist as a global variable?  If not, then as-if says it doesn't have
to exist.  The program can tell that f was called, but I'd expect
there to be weasel words to the effect that the initialization
expression of a templated static data member may not be evaluated if
the template is never instantiated (or the program can't tell that it
wasn't).

Even if there are no such weasel words, couldn't we arrange to call f
and throw the value away?

If I write two normal functions, one of which refers to S<int> and the
other S<double>, is f called twice?

If your example is in a header file and two files include it, how
do we avoid initializing S<int>::i twice (hence calling f twice)?

zw

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]