static var initialization in static library
Hello,
I have a library (developped with MSVC 2005) containing a class with static
variables. It seems
that when the library is a static lib the initialization of the static
var does not happen, whereas in a exe or dll everything works well.
The only I found about that on the web is still not solved.
Here is the sample code :
// -------- Method class -------- //
//declaration
class Method {
public:
virtual void function() = 0;
static vector<Method*> instances;
};
//definition
vector<Method*> Method::instances;
Method::Method(){
instances.push_back(this);
}
// -------- MethodA class -------- //
//declaration
class MethodA {
public:
virtual void function();
private:
static MethodA self;
};
//definition
MethodA MethodA::self;
void MethodA::function(){
print("I'm method A");
}
// ------------ Main ------------ //
void main(){
print(Method::instances.size());
// = 1 when DLL or EXE, corresponding to MethodA instance
// = 0 when LIB
}
Here the parent class is Method, which is abstract.
Since every implementation of Method has a static member of itself, and no
constructor defined, they are automatically instanciated calling the default
constructor of Method. The effect is that before the execution of the main,
all existing implementation are added to the Method::instances vector.
That virtual constructor pattern does not work with static libraries. I hope
you may explain me what may in the difference between LIB and DLL cause the
problem.
Guillaume