Initializing memory for the compiler

Is there a way to ensure the initialization order of a static object for certain objects for the entire program. I have memory allocators that I would like to allocate as the first thing in the program, since they will be used even where throughout the program, and I want to use these allocators to allocate all subsequent memory.

I understand that this is probably a specific compiler, since I do not believe the C ++ standard allows this. The two compilers I'm interested in are the gcc and VS2010 compilers. If there is a way, can someone explain how?

EDIT

I don't need a โ€œfirst-use constructโ€ because allocators will allocate a large block of memory that I want to initialize at the beginning of the program.

+7
source share
3 answers

You can slightly influence the initialization order using special directives for the compiler. MSVC has a pragma

#pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} ) 

which can somewhat prioritize a specific module. See this link for init_seg .

The gcc compiler has a similar / related attribute syntax to set the relative priority of a particular initialization. Looks like this

 Some_Class A __attribute__ ((init_priority (2000))); Some_Class B __attribute__ ((init_priority (543))); 

and explained on this page init_priority .

+7
source

I assume that you mean the static initialization order fiasco, so your program has the ability to trigger undefined behavior when the static variable is initialized based on the state of another static variable (which may or may not have its own constructor, called at that time).

A workaround to this problem is the construction used when using the idiom for the first time, described in the C ++ FAQ:

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15

0
source

Instead of trying to manage static initialization, which will only cause hours or more ridiculous debugging times in the future, allocate your memory pool at the beginning of main . Then you still get your preallocated memory without any static init errors.

0
source

All Articles