in GeneralPurposeAllocator.allocator()
, the following code is used to create an Allocator
:
pub fn allocator(self: *Self) Allocator {
return .{
.ptr = self,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.free = free,
},
};
}
I have a very basic question about this: what language mechanism ensures that the vtable pointed to here has global lifetime, rather than being created on the stack during the allocator()
function (so no longer valid when the function returns)?
I would have expected something like the following to ensure that returned allocator points to a VTable with long enough lifetime:
const vtable: Allocator.VTable = .{
.alloc = alloc,
.resize = resize,
.free = free,
};
pub fn allocator(self: *Self) Allocator {
return .{
.ptr = self,
.vtable = &vtable,
};
}
Why is the above not necessary in this case? Thanks!