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?
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):and in one translation unit you have to provide a definition of
init_library::counter.This will put a static object of type
init_libraryin 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”.