82 C++对象模型探索。数据语义学 - 单一继承下的数据成员布局

在使用继承后,由于内存对齐的影响,会带来内存空间的额外增加。

windows 和 linux 的图示:

82 C++对象模型探索。数据语义学 - 单一继承下的数据成员布局_第1张图片

82 C++对象模型探索。数据语义学 - 单一继承下的数据成员布局_第2张图片

对于windows,在继承时,子类中应该包含父类的全部,包括了父类内存对齐时空的内存部分。

对于linux,编译器会有优化,会将最终子类和直接父类融合,利用上一个父类因为内存对齐浪费的空间。这个是从实验看到结果后,个人的想法。linux的G++编译器不可能将父类的父类的内存的空间都改变,优化也只能优化最终子类和最终子类的爸爸。

在linux上就会有一个问题,因为g++做了优化,因此使用memcpy这类mem相关的操作要注意。

class Teacher8 {
public:
	int age1;
	char ch1;
	char ch2;
	char ch3;
};

class Teacherbase8 {
public:
	int age1;
	char ch1;
};

class Teacher81 : public Teacherbase8 {
public:
	char ch2;
};

class Teacher82 : public Teacher81 {
public:
	char ch3;
};


void main() {
	cout << sizeof(Teacher8) << endl; //大小占用为8,且是紧凑的
	printf("Teacher8::age1的偏移量是:%p\n", &Teacher8::age1);
	printf("Teacher8::ch1的偏移量是:%p\n", &Teacher8::ch1);
	printf("Teacher8::ch2的偏移量是:%p\n", &Teacher8::ch2);
	printf("Teacher8::ch3的偏移量是:%p\n", &Teacher8::ch3);

	//8
	//	Teacher8::age1的偏移量是:00000000
	//	Teacher8::ch1的偏移量是:00000004
	//	Teacher8::ch2的偏移量是:00000005
	//	Teacher8::ch3的偏移量是:00000006

	//如果我们将Teacher8使用集成拆分,再来看一下内部布局会不会发生变化。

	cout << sizeof(Teacher81) << endl; //大小占用为12,
	printf("Teacher81::age1的偏移量是:%p\n", &Teacher81::age1);
	printf("Teacher81::ch1的偏移量是:%p\n", &Teacher81::ch1);
	printf("Teacher81::ch2的偏移量是:%p\n", &Teacher81::ch2);
	//12
	//	Teacher81::age1的偏移量是:00000000
	//	Teacher81::ch1的偏移量是:00000004
	//	Teacher81::ch2的偏移量是:00000008

	cout << sizeof(Teacher82) << endl; //大小占用为16,
	printf("Teacher82::age1的偏移量是:%p\n", &Teacher82::age1);
	printf("Teacher82::ch1的偏移量是:%p\n", &Teacher82::ch1);
	printf("Teacher82::ch2的偏移量是:%p\n", &Teacher82::ch2);
	printf("Teacher82::ch3的偏移量是:%p\n", &Teacher82::ch3);

	//16
	//	Teacher82::age1的偏移量是:00000000
	//	Teacher82::ch1的偏移量是:00000004
	//	Teacher82::ch2的偏移量是:00000008
	//	Teacher82::ch3的偏移量是:0000000C
}

你可能感兴趣的:(c++,算法)