定义全局作用域的对象,该对象的构造函数会在程序运行之前执行,也就是在main函数之前执行。析构函数在main之后执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#define RegisterBuilderByType(BuilderClassName, type) \
ExecuteBeforeMain(BuilderClassName){\
theFactory->registerWidget(new (BuilderClassName), type);\
}
#define ExecuteBeforeMain(ClassName)\
struct ExecuteBeforeMain##ClassName{\
ExecuteBeforeMain##ClassName();\
}__##ExecuteBeforeMain##ClassName;\
ExecuteBeforeMain##ClassName::ExecuteBeforeMain##ClassName()
展开 RegisterBuilderByType(MyBuilderClass, MyType); 的步骤如下:
ExecuteBeforeMain(MyBuilderClass) {
theFactory->registerWidget(new (MyBuilderClass), MyType);
}
继续展开:
struct ExecuteBeforeMainMyBuilderClass {//定义了一个结构体,并在内部定义了一个构造函数
ExecuteBeforeMainMyBuilderClass();
} __ExecuteBeforeMainMyBuilderClass;//在全局作用域中创建了一个名为__xxx的对象,这样程序运行之前会自动执行该对象的构造函数。
ExecuteBeforeMainMyBuilderClass::ExecuteBeforeMainMyBuilderClass() {
theFactory->registerWidget(new (MyBuilderClass), MyType);
}