How to override the .new procedure?

Next step in creating my own prelude. Let’s say I have a custom allocator and want to use that to create class instances by calling .new. But even with an empty prelude Crystal seems to use an internal allocator, defining def new in class Object doesn’t help.

I realized I misunderstood your question, so I deleted my earlier reply.
I can’t really answer something this complex myself, but I found that DeepWiki can be helpful in cases like this. It looks through the codebase and gives relevant information.

For example, instead of overriding .new, it points out that you can use pre_initialize to implement a custom allocator.

pre_initialize is for when you want to explicitly manage allocation of a particular instance.

I presume you want to customize all allocations for all instances of all classes, though. For that, you need to define GC.malloc, GC.malloc_atomic.
For reference, see the implementation in gc/none. These methods are called implicitly as part of the autogenerated .new methods (through .allocate and __crystal_malloc64, __crystal_malloc_atomic64).

If you would want to customize all allocations behaviour for all instances of a specific class, you could override the respective .allocate method instead.

1 Like