Suppose I need to call a free GlobalInitializer() before my constructor initializes any member variables. For example:
class Foo {
public:
Foo() : bar_()
{
// calling GlobalInitializer() here is too late
}
Bar bar_;
};
Calling GlobalInitializer() in Foo is too late because I need to call it before bar_ is initialized. My hacky work around for this has been to create a super-class:
class MyInitializer {
protected:
MyInitializer() {
GlobalInitializer();
}
};
class UglyFoo : public MyInitializer
{
public:
UglyFoo() : bar_()
{ }
Bar bar_;
};
UglyFoo gets the job done, but it requires this ugly MyInitializer class. Is there a cleaner design pattern or refactoring which will achieve the same result?
Additional Note: GlobalInitializer() is an expensive call that I want to avoid unless the user instantiates a Foo(). There are guards inside GlobalInitializer() against multiple calls. Also, there may be other classes, say FooBar, that also need to call GlobalInitializer(), but in one process, GlobalInitializer() will actually do work once (if Foo or FooBar is instantiated) or not even once (if there are no instantiations of Foo or FooBar).
1 Answer