(no title)
tiehuis | 8 years ago
Zig doesn't have a default memory allocator. Allocators instead are expected to be passed as an argument to functions as they need them. This makes it trivial to replace an allocator with something custom or use multiple different allocators within a small code block.
A contrived example:
const std = @import("std");
pub fn GiveMeAnInt(alloc: &std.mem.Allocator) -> %&u32 {
return alloc.create(u32);
}
test "using two allocators" {
const int1 = try GiveMeAnInt(std.heap.c_allocator);
*int1 = 2;
// Would usually store the allocator with the type on construction.
defer std.heap.c_allocator.destroy(int1);
const int2 = try GiveMeAnInt(std.debug.global_allocator);
*int2 = 2;
}
No comments yet.