Hi everyone,
I have the following weird problem (working on a library):
I have an abstract class ExportFilter, that has a static element Factory<ExportFilter>. The intention is that the derived classes are registered there so you can instantiate them.
export.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class ExportFilter
{
public:
static Factory<ExportFilter> ExportFilterFactory;
...
};
class ExportFilterDOT : public ExportFilter
{
...
};
class ExportFilterGASTEX : public ExportFilter
{
...
};
... (more derived classes)
|
now to register them, I (globally) instantiate FactoryRegistrator<ExportFilter> objects. these are "dummy"-objects, that are only there so that their constructor is executed - the constructor registers the class at the factory.
So I can enforce the RegisterClass calls within the library and don't have to worry whether some initialization-code is called from a program using my library.
export.cpp
1 2 3 4
|
#include "export.h"
...
Factory<ExportFilter> ExportFilter::ExportFilterFactory;
...
|
dot.cpp
1 2 3 4 5
|
#include "export.h"
...
FactoryRegistrator<ExportFilter> ExportFilterDotRegistrator(
&ExportFilter::ExportFilterFactory, "dot", new DefaultInstantiator<...>(...));
...
|
gastex.cpp
1 2 3 4 5
|
#include "export.h"
...
FactoryRegistrator<ExportFilter> ExportFilterGastexRegistrator(
&ExportFilter::ExportFilterFactory, "gastex", new DefaultInstantiator<...>(...));
...
|
When I run a program using the library, I get a segmentation fault.
If I comment out the FactoryRegistrator for ExportFilterDot, it works (I dont't have to comment out any other Registrator) but then I cannot instantiate ExportFilterDOT using the factory...
The problem seems to be, that the ExportFilterDotRegistrator is initialized before the ExportFilter::ExportFilterFactory is initialized, so passing the Factorys address to the FactoryRegistrator's constructor causes the segmentation fault...
I guess that's because dot.cpp lexicographically comes before export.cpp, so it's objects are initialized first (gastex.cpp and all others come after export.cpp)
Shouldn't the linker get this right? I mean dot.cpp includes export.h, where the Factory is declared. shouldn't the linker see that the factory must be initialized first, because (by inclusion of export.h) dot.cpp says that it expects to be able to use the factory?
And more importantly, how can I circumvent this problem? I don't really want a tinkered solution like giving dot.cpp a less self-explanatory filename...
Thanks in advance for any help :-)
cya
Viktor