当我们声明一个类的对象时,它的内存布局是否连续(一个接一个)?如果它是连续的,那么填充会发生在它里面(比如结构填充) ?请帮助我了解类的内存布局
提前致谢。
最佳答案
When we declare object of a class is its memory allocation successive(One after the other)?
标准不提供任何此类保证。对象内存布局是实现定义的。
通常,数据成员的内存地址按照它们在类中定义的顺序递增。但在遇到访问说明符(private
、protected
、public
)的任何地方,此顺序都可能被打乱。这已在 Inside the C++ Object Model 中进行了非常详细的讨论。作者:李普曼。
摘自 C/C++ Users Journal ,
The compiler isn't allowed to do this rearrangement itself, though. The standard requires that all data that's in the same public:, protected:, or private: must be laid out in that order by the compiler. If you intersperse your data with access specifiers, though, the compiler is allowed to rearrange the access-specifier-delimited blocks of data to improve the layout, which is why some people like putting an access specifier in front of every data member.
很有趣,不是吗?
关于c++ - 一个类的内存布局是连续的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4842434/