版本
gcc version 7.5.0 (Ubuntu 7.5.0-6ubuntu2)
Linux UM480XT 5.15.0-107-generic #117~20.04.1-Ubuntu SMP Tue Apr 30 10:35:57 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux
Microsoft Visual Studio Enterprise 2019, _MSC_VER == 1929
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void on_exit()
{
printf("%s()\n", __func__);
}
class Foo
{
public:
Foo(int32_t i) :
m_i(i)
{
printf("%s(%d)\n", __func__, m_i);
}
~Foo()
{
printf("%s(%d)\n", __func__, m_i);
}
int32_t m_i = 0;
};
static Foo g_foo(1);
Foo g_foo2(2);
static Foo g_foo3(3);
void un_call()
{
static Foo foo7(7);
Foo foo8(8);
}
int main(int argc, char **argv)
{
Foo foo7(7);
static Foo foo4(4);
Foo foo6(6);
::atexit(on_exit);
static Foo foo5(5);
printf("------\n");
return 0;
}
与优化不优化无关系
顺序
构造函数调用顺序
全局变量/全局静态变量(按声明顺序构造) > 局部变量/局部静态变量(按声明顺序构造)
析构函数调用顺序
局部变量(先构造的后析构) > 在atexit函数后构造的局部静态变量 > atexit回调函数 > 局部静态变量(先构造的后析构) > 全局静态/全局变量(先构造的后析构)
不同源文件之间的 全局变量/全局静态变量 的构造顺序取决于链接顺序
如
test_1.cc
test_2.cc
两个文件
g++ test_1.cc test_2.cc -O2
那么先构造test_1
文件的全局变量/全局静态变量
,并且析构时间晚于test_2.cc
调换顺序后则先构造test_2