class attributes/fields 是如何存储的

How are class attributes/fields stored

我知道这个 C++ class 的一个实例:

class A {
   char c;
   int iiii;
   short ss;   
};

在记忆中看起来像这样:c| | | |i|i|i|i|s|s| | |

这个4/2字母注释没有任何意义(但我认为我的观点很明确)

1 byte for char3 bytes of padding4 bytes of int2 bytes for the short2 bytes of tail padding(平台相关,但不会改变逻辑)

来自 C++ 标准(编译器不会更改我示例中字段的顺序):

Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (Clause 11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).

所以,我想知道 Java classes 是否相同,编译器可以更改顺序以减少填充吗?

先看看What do Java objects look like in memory during run-time? and Know Thy Java Object Memory Layout

但我想 Java Objects Memory Structure 回答了你的问题。

In order to save some memory, the Sun VM doesn't lay out object's attributes in the same order they are declared. Instead, the attributes are organized in memory in the following order:

doubles and longs
ints and floats
shorts and chars
booleans and bytes
references