一、对于局部对象(当程序执行流执行到对象的定义语句时进行构造)
int i = 0;
Test a1 = i;//a1第一个被定义,所以第一个被构造
while(i < 3)
Test a2 = ++i;//第二个被定义,第二个被构造
if(i < 4)
Test a = a1;
else
Test a(100);
include using namespace std; class Test { private: int mi; public: Test(int v) { mi = v; cout<<”Test(int v) = “<
二、对于堆对象
当程序执行流到达new语句时创建对象
当new时会自动调用构造函数
int i = 0;
Test *a1 = new Test(i);//a1第一个new,所以第一个被构造
while(++i < 10)
if(i % 2)
new Test(i);//第二个new,第二个被构造
if(i < 4)
new Test(*a1);
else
new Test(100);
#include<iostream>
using namespace std;
class Test
{
private:
int mi;
public:
Test(int v)
{
mi = v;
cout<<"Test(int v) = "<<mi<<endl;
}
Test(const Test& obj)
{
mi = obj.mi;
cout<<"Test(const Test& obj)="<<mi<<endl;
}
};
int main()
{
int i = 0;
Test *a1 = new Test(i);// Test(int v) = 0
while(++i<10)
if(i%2)
new Test(i);//Test(int v) = 1 3 5 7 9
if(i<4)
new Test(*a1);
else
new Test(100);Test(int v) = 100
cin.get();
return 0;
}
堆对象的构建也会受goto语句的影响,因为goto语句会影响程序的执行流
三、对于全局对象
对象的构造顺序是不确定的
不同的编译器使用不同的规则来确定构造顺序
全局对象的构造是在main函数开始之前,没进入main函数就没有所谓的程序执行流,故要是有多个全局对象时,构造的顺序就不确定了
所以就要尽量避开全局对象间的依赖
test.h:
#ifndef _TEST_H_
#define _TEST_H_
#include<iostream>
using namespace std;
class Test
{
public:
Test(const char* s)
{
cout<<s<<endl;
}
};
#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");
main.cpp:
#include"test.h"
Test t4("t4");
int main()
{
Test t5("t5");
cin.get();
return 0;
}
在不同的编译器中输出的结果不一样,但t5都是在最后的
小结:
1.局部对象的构造顺序依赖程序的执行流
2.堆对象的构造顺序依赖于new语句的执行顺序
3.全局对象的构造顺序是不确定的