help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Compiler doesn't create some static class members


From: Johan_De_Taeye
Subject: Compiler doesn't create some static class members
Date: 1 Feb 2005 08:22:08 -0800

Dear gurus, 

I have the impression that G++ uses some logic to choose whether or
not to instantiate static data members. My initial expectation was
that static data members would be created unconditionally.
I'ld like to understand better what's happening here and how I can
force the instantiation in an easy and clean way.

Let me explain with some code:
   
In my header file I have a class for storing some metadata:

  class metadata {
    public:
      // Simplified. the real constructor takes additional parameters,
such as
      // a function pointer to a factory method
      metadata(const string& s) {cout << "metadata for " << s <<
endl;}
  }

  class A {
    static const metadata meta;
  }
   
  ...

  class Z {
    static const metadata meta;
  }

Across my various source files, I then instantiate each of the static
members:

  ...
  const metadata A::metadata("my class A");
  ...


The following behavior is noticed:
- when the number of source files with static member definitions
increases, not all of my metadata objects are being created.
- when I move all the definitions of the static objects into a single
file, all objects are created as expected.  Strange...
- when multiple static libraries (each with a certain set of static
metadata objects) are being linked together, only static members of
one of the libraries are created.
- When I explicitly reference the metadata object of a class in the
main application, that metadata object is created correctly. Looks
like a way to force the instantiation, albeit clumsy.

I am using G++ 3.3.3 with cygwin, and also noticed the same/similar
behavior in Visual C++ 6. Borland 5.5.1 is nice to me and creates the
objects unconditionally.

All hints, explanations and solutions are highly appreciated!

Regards,

Johan


BTW: if there are better ideas around to build such a simple metadata
framework, I am listening and willing to learn...


reply via email to

[Prev in Thread] Current Thread [Next in Thread]