在静态成员分配之前调用函数 [英] Call a function before static member allocation
问题描述
我使用第三方API覆盖C运行时库中的内存管理功能。为了使一切正常工作,我必须调用在初始化API之前进行任何内存分配。
我正在使用的项目使用一个静态的Factory对象,在主文件中的任何代码执行之前动态初始化。
如何确保API将在静态Factory对象之前初始化?
标准库运行到相同的问题:它必须确保在任何代码之前初始化 cin
, cout
,包括静态对象的构造函数,使用它们。为了处理这种情况而发明的伎俩也可以解决你的问题。在每个翻译单元中都包含第一的头文件(以及每个包含具有动态初始值设置的静态对象的翻译单元):
class init_library {
public:
init_library(){if(counter ++ == 0)initilaize_the_library }
private:
static int counter;
};
static init_library i_library;
并且在一个翻译单元中必须提供 init_library ::计数器
。
这将在每个翻译单元中放置一个 init_library
拉动标题。它的初始化将在之前在同一翻译单元中进行任何其他初始化之前发生(因为它的#include指令第一) - 不要忘记!),第一次这些对象之一被初始化,它将调用代码来初始化库。 (注意,这个代码不是线程安全的,使它线程安全是很简单的)
这就是所谓的 b $ b
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):
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".
这篇关于在静态成员分配之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!