> Im getting a runtime error because Ive got a static object that is not
> properly initialized.
[quoted text clipped - 4 lines]
> } // end SomeClass
> static SomeClass staticObject; // declaration in header
That's probably not what you wanted. Change this to
extern SomeClass staticObject;
As is, you're creating an instance of the object in every translation unit
that includes the header.
> -------------- in .cpp file: ----
> SomeClass staticObject; // definition in .cpp file: constructor
[quoted text clipped - 7 lines]
> okay for integers, floats, simple arrays (of ints, floats), char[]
> strings, and for classes (or structs) that DO NOT have a constructor.
Globals/statics that have constructors are perfectly fine, but you have to
be careful when accessing one static object from within the constructor of
another static object as the order of initialization guarantees provided by
the C++ language specification are well... weak.
> But, he says, one should never use a static/global for an object of a
> class that has a constructor, because the loader is very
[quoted text clipped - 7 lines]
> PS: I should mention that this software is in a DLL (not an
> application) that is attached to processes at run time, not link time.
-cd
noleander - 23 Aug 2006 15:36 GMT
Thanks for the tip. The actual code I have (my snippet above simplified
things) is:
---------- header file xxx.hpp ---------------
class SomeClass {
SomeClass() { .. constructor here ..;}
} // end SomeClass
class OtherClass {
static SomeClass staticObject; // static data member
....
}
---------- xxx.cpp file -----------
static OtherClass::staticObject = {...};
> > That's probably not what you wanted. Change this to
>
> extern SomeClass staticObject;
>
> As is, you're creating an instance of the object in every translation unit
> that includes the header.
Carl Daniel [VC++ MVP] - 23 Aug 2006 15:48 GMT
> Thanks for the tip. The actual code I have (my snippet above
> simplified things) is:
[quoted text clipped - 11 lines]
> ---------- xxx.cpp file -----------
> static OtherClass::staticObject = {...};
Oh, OK. That's completely different and should be fine. Constructors for
such objects definitely will run, but the order of constructor execution
between globals decalred in different translation units is undefined. If
you're entering this object from another global object constructor in a
different translation unit, you may well touch this object before it's
constructor is run.
-cd