c++ 局部变量 全局变量 atexit注册函数 析构顺序

析构先后顺序为:局部变量、mian函数中注册atexit函数、全局变量及在其中注册atexit函数(全局变量和在全局变量中注册atexit函数析构顺序与构造顺序相反)。测试代码如下(gcc-4.6.3编译, ubuntu 12.04 linux 内核3.2.0运行):

#include 
#include 
#include 
#include 

static void PrintCurTime()
{
	clock_t t = clock();
	printf("past seconds %d\n", t);
}

static void exit_0()
{
	printf("exit_0\n");
}

static void exit_1()
{
	printf("exit_1\n");
}

class A
{
public:
	A(const char* name)
	{
		m_name = name;
		printf("A::A() %s\n", m_name);
	}
	~A()
	{
		printf("A::~A() %s\n", m_name);
		double sum = 0;
		const int n = 1<<28;
		for (int i = 0; i < n; ++i)
		  sum += i*i;
	}

	const char* m_name;
};

class B
{
public:
	B(const char* name)
	{
		m_name = name;
		printf("B::B() %s\n", m_name);
		atexit(exit_0);
	}
	~B(){printf("B::~B() %s\n", m_name);}

	const char* m_name;
};

void FunInMain()
{
	A a("a_FunInMain");
}

B g_b("g_b");
A g_a("g_a");

int main(int argc, char* argv[])
{
	printf("enter main");

	atexit(PrintCurTime);

	atexit(exit_0);

	A a1("a1");

	FunInMain();

	atexit(exit_1);

	A a2("a2");

	printf("exit main");

	return 0;
}

运行结果:

B::B() g_b
A::A() g_a
enter mainA::A() a1
A::A() a_FunInMain
A::~A() a_FunInMain
A::A() a2
exit mainA::~A() a2
A::~A() a1
exit_1
exit_0
past seconds 3810000
A::~A() g_a
B::~B() g_b
exit_0


将全局变量g_b和g_a声明顺序颠倒,运行结果:

A::A() g_a
B::B() g_b
enter mainA::A() a1
A::A() a_FunInMain
A::~A() a_FunInMain
A::A() a2
exit mainA::~A() a2
A::~A() a1
exit_1
exit_0
past seconds 3810000
B::~B() g_b
exit_0
A::~A() g_a



你可能感兴趣的:(C++)