Function call before static member allocation

I use a third-party API that overrides the memory management functions found in the C runtime libraries. For everything to work correctly, I have to make a call to initialize the API before the memory is allocated.

The project I'm 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 guarantee that the API will be initialized to a static Factory object?

0
c ++ memory-management design-patterns static-members
source share
2 answers

The C ++ standard library faces the same problem: it must ensure that cin , cout , etc. initialized before any code uses them, including constructors for static objects. The trick that was invented to solve this situation can also solve your problem. In the header file, which includes the first in each translation unit (well, each 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 must provide the definition init_library::counter .

This will result in a static object of type init_library in each translation unit that is pulled into the header. Its initialization will occur before any other initialization in the same translation unit (since its #include directive appeared first - do not forget about it!), And for the first time one of these objects is initialized, it will call the code to initialize the library. (Note that this code is not thread safe, which makes it thread safe directly)

This is called a "great trick."

+5
source share

You have to transfer the static initialization of the factory objects to a static function and call this function after initializing the third party as the first thing basically.

+5
source share

All Articles