函数在main之前或之后运行
  • C++中,全局对象的构造函数在main之前运行,析构函数在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
25
26
27
class Base
{
public:
Base()
{
std::cout<<"基类构造"<<endl;
}
~Base()
{
std::cout<<"基类析构"<<endl;
}
static int get()
{
std::cout<<"get()"<<endl;
return 55;
}
static int count;
}

// main.cpp
Base b;
// int Base::count = Base::get(); 错误,这里不能调静态函数
int main()
{
std::cout<<"main "<<endl;
return 0;
}

运行结果:

1
2
3
4
基类构造
get()
main
基类析构

gcc中使用attribute关键字,声明constructor和destructor函数:

1
2
3
4
5
6
7
__attribute__((constructor)) void before_main() { 
printf("before main\n");
}

__attribute__((destructor)) void after_main() {
printf("after main\n");
}

如何在程序退出时运行函数

很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit()结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法,在退出时执行某函数。方法就是用atexit()函数来注册程序正常终止时要被调用的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdlib>

void atexit_handler_1()
{
std::cout << "at exit #1\n";
}

void atexit_handler_2()
{
std::cout << "at exit #2\n";
}

QApplication a(argc, argv);

const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);

if ((result_1 != 0) || (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
MainWindow w;
w.show();
return a.exec();

atexit执行成功,返回0,否则返回非0.

当程序正常终止(调用exit()或者由main函数返回)时,调用atexit()参数中指定的函数。