C++结构体内存布局差异问询:含成员函数的结构体是否改变布局?
Great question! Let's break this down clearly for you.
First, the key point to remember: member functions (like B::foo()) do NOT take up space in individual instances of your struct.
Here's why: Member functions are part of the struct's "type information" stored in the program's code segment, not duplicated for every instance you create. When you call foo() on a B object, the compiler implicitly passes a pointer to that object (the this pointer) to the function—but that pointer isn't stored inside the object itself.
So, for your specific examples:
- The memory layout of a
struct Ainstance is exactly the same as astruct Binstance. Both will have theint a,double b, andfloat cmembers laid out in the same order, with the same padding (if any) for alignment, and the same total size. - If you check
sizeof(A)andsizeof(B)with a standard-compliant compiler, they'll return the exact same value.
Wait, what if we added a virtual function? Then things would change—struct instances would include a hidden pointer to a virtual function table (vtable), which adds to the size and alters the layout. But in your case, B::foo() is a non-virtual member function, so no extra overhead is added to the struct's memory footprint.
To sum up: Adding non-virtual member functions to a struct doesn't change how its data members are arranged in memory. Only data members (and virtual function pointers, if any) affect the instance's memory layout.
内容的提问来源于stack exchange,提问作者Iliketoproveit

