本文学习自 狄泰软件学院 唐佐林老师的 C++课程
实验1: 局部对象的创建顺序–当程序执行流到达对象的定义语句时进行构造
实验2:对于全局对象,对象的构造顺序是不确定的,不同的编译器使用不同的规则确定构造顺序
实验1: 局部对象的创建顺序–当程序执行流到达对象的定义语句时进行构造
#include <stdio.h>
class Test
{
private:
int mi;
public:
Test(int i)
{
mi = i;
printf("Test(int i): %d\n", mi);
}
Test(const Test& obj)
{
mi = obj.mi;
printf("Test(const Test& obj): %d\n", mi);
}
};
int main()
{
int i = 0;
Test a1 = i;
while( i < 3 )
{
Test a2 = ++i;
}
if( i < 4 )
{
Test a = a1;
}
else
{
Test a(100);
}
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 21-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
Test(int i): 0
Test(int i): 1
Test(int i): 2
Test(int i): 3
Test(const Test& obj): 0
mhr@ubuntu:~/work/c++$
实验2:对于全局对象,对象的构造顺序是不确定的,不同的编译器使用不同的规则确定构造顺序
test.h
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
class Test
{
public:
Test(const char* s)
{
printf("%s\n", s);
}
};
#endif
t1.cpp
#include "test.h"
Test t1("t1");
t2.cpp
#include "test.h"
Test t2("t2");
t3.cpp
#include "test.h"
Test t3("t3");
21-3.cpp
#include "test.h"
Test t4("t4");
int main()
{
Test t5("t5");
}
.
mhr@ubuntu:~/work/c++$ g++ t3.cpp t2.cpp t1.cpp 21-3.cpp -o test.out
mhr@ubuntu:~/work/c++$ ./test.out
t3
t2
t1
t4
t5
mhr@ubuntu:~/work/c++$
我们以同样的方式到windows 用 VC++编译器编译同样的代码,结果如下:
结论 :所以不同的编译器对于全局对象的构造顺序是完全不一样的,所以我们在开发的时候要避开不同全局对象之间的相互依赖。