Call a function before static member allocation

2020-03-08 06:04发布

问题:

I am using a 3rd party API that overrides the memory management functions found in the C Runtime libraries. In order for everything to work properly, I must make a call to initialize the API before any memory allocations take place.

The project I am working on uses a static Factory object that is dynamically initialized before any of the code in the main file is executed.

How can I ensure that the API will be initialized before the static Factory object?

回答1:

The C++ standard library runs into the same problem: it has to ensure that cin, cout, etc. are initialized before any code, including constructors for static objects, uses them. The trick that was invented for handling this situation can also solve yours. In a header file that gets included first in every translation unit (well, every translation unit that has static objects with dynamic initializers):

class init_library {
public:
    init_library() { if (counter++ == 0) initilaize_the_library(); }
private:
    static int counter;
};

static init_library i_library;

and in one translation unit you have to provide a definition of init_library::counter.

This will put a static object of type init_library in every translation unit that pulls in the header. Its initialization will happen before any other initialization in that same translation unit (because its #include directive came first -- don't forget that!), and the first time that one of these objects gets initialized, it will call the code to initialize the library. (Note that this code is not thread-safe; making it thread-safe is straightforward)

This is known as the "nifty counter trick".



回答2:

You should move your static factory objects initilization to a static function and call that function after initializing 3rd party lib as a first thing in main.