How class attributes / fields are stored

I know an instance of this C ++ class:

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

will look something like this in memory: c| | | |i|i|i|i|s|s| | | c| | | |i|i|i|i|s|s| | |

This 4/2 letter annotation makes no sense (but I think my point is clear)

1 byte for char , 3 bytes of padding , 4 bytes of int , 2 bytes for the short and 2 bytes of tail padding (platform dependent, but this will not change the logic)

From C ++ standards (compilers won't change the order of fields in my example):

Non-static data members of a (non-unitary) class with the same access (section 11) are allocated so that later members have higher addresses inside the class object. The distribution order of non-static data members with different access controls is not defined (clause 11). Implementation alignment requirements can cause two neighboring members not to stand out immediately after each other; so the space requirements for managing virtual functions (10.3) and virtual base classes (10.1).

So, I would like to know if this is the same for Java classes. Can the compiler reorder to reduce padding?

+7
java c ++ alignment class padding
source share
1 answer

First take a look at What Java objects look like in memory at runtime? and Know your Java object memory structure .

But I think Java Objects Structure answers your question.

To preserve some memory, Sun VM does not expose the attributes of an object in the same order in which they are declared. Instead, attributes are organized into memory in the following order:

 doubles and longs ints and floats shorts and chars booleans and bytes references 
+1
source share

All Articles