instance_alignof

The instance_alignof expression returns an Int32 with the instance alignment of a given class.

Unlike alignof which would return the alignment of the reference (pointer) to the allocated object, instance_alignof returns the alignment of the allocated object itself.

For example:

  1. class Foo
  2. end
  3. class Bar
  4. def initialize(@x : Int64)
  5. end
  6. end
  7. instance_alignof(Foo) # => 4
  8. instance_alignof(Bar) # => 8

Even though Foo has no instance variables, the compiler always includes an extra Int32 field for the type id of the object. That’s why the instance alignment ends up being 4 and not 1.