C++中class大小的决定因素详解

一、非静态成员变量的大小

#include <iostream>
using namespace std;

class A {
    static int a; // 4字节
    int c;   // 4字节
    int i;    // 4字节
};

int main() {
    cout << sizeof(A) << endl;  // 输出8
}

解析:

  • int c(4字节) + int i(4字节) = 8字节


二、内存对齐(Alignment)和填充(Padding)

#include <iostream>
using namespace std;

class B {
    char c;     // 1字节
    double d;   // 8字节
};

int main() {
    cout << sizeof(B) << endl;  // 输出16
}

解析:

  • 为8字节对齐,结构为:

  • char c(1字节) + 填充7字节 + double d(8字节) = 16字节


三、虚函数的影响(虚函数表指针)

#include <iostream>
using namespace std;

class C {
    virtual void f() {}  // 引入vptr指针 8字节
    int x; // 4 + 4
};

int main() {
    cout << sizeof(C) << endl;  // 输出16
}

解析:

  • 虚函数表指针(vptr):8字节

  • int x:4字节 + 4字节填充 = 16字节


四、虚继承的影响(虚基类指针)

#include <iostream>
using namespace std;

class Base {
    int a;
};

class Derived : virtual public Base {
    // vbptr # 8字节 
    int b; // 4字节
    //int a; // 4字节
};

int main() {
    cout << sizeof(Derived) << endl;  // 输出16
}

解析:

  • 虚继承加入虚基类指针(vbptr):8字节

  • 自身成员int b(4字节) + 填充4字节 = 16字节


五、空类大小为1的原因

#include <iostream>
using namespace std;

class Empty {};

int main() {
    cout << sizeof(Empty) << endl;  // 输出1
}

解析(重点):

  • 空类大小不是0字节,而是至少1字节。

  • 因为C++标准要求每个对象都有独立、唯一的内存地址,若为空类大小为0字节,多个空类实例就无法拥有不同地址,因此至少分配1字节空间以确保地址独立性。


【总结表格】

因素影响类大小情况
非静态成员变量按类型大小累计
内存对齐(Padding)补齐字节以满足对齐要求
虚函数产生虚函数表指针(vptr)
虚继承产生虚基类指针
空类最小为1字节,确保地址独立

视频链接:

关注微信公众号 程序员陈子青 解锁你的高薪offer之旅。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员陈子青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值