C/C++内存布局

1. C 结构体的内存布局

以一个例子来看struct的内存结构


#define NP_FUNC_WRAPPER __attribute__((optimize(0)))

struct StructBody
{
    int first_int_placeholder;
    int second_int_placeholder;
    double third_double_placeholder;
};

class ClassBody
{
    public:

    int first_int_placeholder;
    int second_int_placeholder;
    double third_double_placeholder;
};

class SecondClass
{
    public:
    virtual void function_call(){}

    private:
    int first_int_placeholder;
    int second_int_placeholder;
    double third_double_placeholder;

};

#include 

  int main(int argc, char ** argv)
{
    
    int s_struct=  sizeof(StructBody);
    int s_class=  sizeof(ClassBody);
    int s_v_class=  sizeof(SecondClass);
    printf("sizeof(StructBody) = %d, sizeof(ClassBody) = %d, sizeof(SecondClass)=%d\n",
    s_struct, s_class, s_v_class);
    return 0;
}

使用g++编译器(-O3 -std=c++11 -fno-inline-small-functions)产生的汇编代码为:

.LC0:
        .string "sizeof(StructBody) = %d, sizeof(ClassBody) = %d, sizeof(SecondClass)=%d\n"
main:
        sub     rsp, 8
        mov     ecx, 24
        mov     edx, 16
        xor     eax, eax
        mov     esi, 16
        mov     edi, OFFSET FLAT:.LC0
        call    printf
        xor     eax, eax
        add     rsp, 8
        ret

可以看出来,sizeof(StructBody) = 16, 这是因为在64位平台,sizeof(int)=4, sizeof(double)=8

2. C++ 类对象的内存布局

同上,
sizeof(ClassBody) = 16,sizeof(SecondClass)=24,相ClassBody, SecondClass多了8bytes,这是因为SecondClass中有一个virtual function,会在class的开始位置创建一个vtable,本质是一个指针,指向一块内存区域,该区域存放虚函数的地址,因此多了8bytes.

参考:

C++对象在内存中的布局
C++ 对象的内存布局-实验

你可能感兴趣的:(C++学习,c++)