gpt4 book ai didi

c++ - 子类的 sizeof 并不总是等于父类(super class)的 sizeof 之和。那么未使用的内存是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:54 25 4
gpt4 key购买 nike

我写的代码:

#include <iostream>

using std::cout;
using std::endl;

struct S
{
long l;
};

struct A
{
int a;
};

struct B : A, S{ };

int main()
{
cout << "sizeof(A) = " << sizeof(A) << endl; //4
cout << "sizeof(S) = " << sizeof(S) << endl; //8
cout << "sizeof(B) = " << sizeof(B) << endl; //16 != 4 + 8
}

demo

为什么我们必须为 B 分配额外的 4 个字节?如何使用这些额外的内存?

最佳答案

B 实例的内存镜像:

int  a; // bytes 0-3
long l; // bytes 4-11

问题:

l 是一个 8 字节的变量,但是它的地址没有对齐到 8 字节。因此,除非底层硬件架构支持未对齐的加载/存储操作,否则编译器无法生成正确的汇编代码。

解决方案:

编译器在变量 a 之后添加一个 4 字节的填充,以便将变量 l 对齐到 8 字节地址。

B 实例的内存镜像:

int  a; // bytes 0-3
int p; // bytes 4-7
long l; // bytes 8-15

关于c++ - 子类的 sizeof 并不总是等于父类(super class)的 sizeof 之和。那么未使用的内存是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com