You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++结构体内存布局差异问询:含成员函数的结构体是否改变布局?

Do Structs with Member Functions Have Different Memory Layouts in 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 A instance is exactly the same as a struct B instance. Both will have the int a, double b, and float c members laid out in the same order, with the same padding (if any) for alignment, and the same total size.
  • If you check sizeof(A) and sizeof(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:36:48