Created
June 3, 2022 00:09
-
-
Save andrewrk/a2612376de390aedee107be0464595b4 to your computer and use it in GitHub Desktop.
a pattern using comptime fields that might be nice for applications that want to use a global allocator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
var gpa_instance: std.heap.GeneralPurposeAllocator(.{}) = .{}; | |
const global_allocator = gpa_instance.allocator(); | |
const S = struct { | |
comptime gpa: std.mem.Allocator = global_allocator, | |
x: i32, | |
}; | |
pub fn main() !void { | |
defer _ = gpa_instance.deinit(); | |
var s: S = .{ .x = 1234 }; | |
try foo(&s); | |
} | |
fn foo(s: *S) !void { | |
const ptr = try s.gpa.create(i32); | |
defer s.gpa.destroy(ptr); | |
ptr.* = s.x; | |
s.x += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment