help-gplusplus
[Top][All Lists]
Advanced

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

Re: Compiler doesn't create some static class members


From: Larry I Smith
Subject: Re: Compiler doesn't create some static class members
Date: Tue, 01 Feb 2005 16:56:48 GMT
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.5) Gecko/20041220

Johan_De_Taeye wrote:
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...

Perhaps it is just your example that is incorrect, but the static
objects for each class must be declared exactly once in some source
file using their variable names, e.g.:

In A.cpp

  // assuming that A.h includes metadata.h...
  #include "A.h"

  // create the static 'meta' variable for class 'A'
  const metadata A::meta("my class A");

In B.cpp

  // assuming that B.h includes metadata.h...
  #include "B.h"

  // create the static 'meta' variable for class 'B'
  const metadata B::meta("my class B");

Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.


reply via email to

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