对象的构造顺序
问题引入
C++中的类可以定义多个对象,那么对象构造的顺序是怎样的?
顺序一
对于局部变量
- 当程序执行流到达对象定义语句时进行构造
#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 getMi()
{
return mi;
}
};
int main()
{
int i = 0;
Test a1 = i;
while(i < 3)
{
Test a2 = ++i;
}
//程序执行流,跳过了a对象的构造,后期使用a会产生灾难性的错误。
goto End;
Test a(100);
End:
printf("a.mi = %d\n",a.getMi());
return 0;
}
//不同c++编译器,可能可以编译通过
/*
test.cpp:37:1: error: jump to label ‘End’ [-fpermissive]
End:
^
test.cpp:35:6: note: from here
goto End;
^
test.cpp:36:7: note: crosses initialization of ‘Test a’
Test a(100);
*/
顺序二
对于堆对象
- 当程序执行流到达new语句时创建对象
- 使用new创建对象将自动触发构造函数的调用
#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 getMi()
{
return mi;
}
};
int main()
{
int i = 0;
Test* a1 = new Test(i); //Test(int i) = 0
while( ++i < 10) //Test(int i) = 1,3,5,7,9
{
if( i % 2)
new Test(i); //不赋值也可以???
}
if( i < 4)
new Test(*a1);
else
new Test(100); //Test(int i) = 100
//尚未delete
return 0;
}
/*
Test(int i) = 0
Test(int i) = 1
Test(int i) = 3
Test(int i) = 5
Test(int i) = 7
Test(int i) = 9
Test(int i) = 100
*/
顺序三
对于全局对象
- 对象的构造顺序是不确定的
- 不同的编译器使用不同的规则确定构造顺序
!!!重要的事情说三遍。
//test.h
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
class Test
{
public:
Test(const char* s)
{
printf("%s\n", s);
}
};
#endif
//t3.c
#include "test.h"
Test t3("t3");
//t2.c
#include "test.h"
Test t2("t2");
//t1.c
#include "test.h"
Test t1("t1");
//21-3.c
#include "test.h"
Test t4("t4");
int main()
{
Test t5("t5");
}
小结:
- 局部变量的构造顺序依赖程序的执行流
- 堆对象的构造顺序依赖于new的使用顺序
- 全局对象的构造顺序是不确定的