Last active
February 5, 2023 19:55
-
-
Save matu3ba/9ad02f43f3b999c311fc9c7e2a436a53 to your computer and use it in GitHub Desktop.
Zig Result-Location-Semantics footgun
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"); | |
fn t1init(alloc: std.mem.Allocator, path1: []const u8) ![]const u8 { | |
const stdout_wr = std.io.getStdOut().writer(); | |
try stdout_wr.writeAll("t1init"); // prevent compiler to optimize away this fn | |
return try alloc.dupe(u8, path1); | |
} | |
fn t2init(alloc: std.mem.Allocator, path2: []const u8) ![]const u8 { | |
_ = path2; | |
_ = alloc; | |
const stdout_wr = std.io.getStdOut().writer(); | |
try stdout_wr.writeAll("t2init"); // prevent compiler to optimize away this fn | |
return error.fail2; | |
} | |
const ResStruct = struct { | |
t1: []const u8, | |
t2: []const u8, | |
fn init(alloc: std.mem.Allocator, path: []const u8) !ResStruct { | |
return .{ | |
.t1 = try t1init(alloc, path), | |
.t2 = try t2init(alloc, path), | |
}; | |
} | |
fn deinit(self: *ResStruct, alloc: std.mem.Allocator) void { | |
alloc.free(self.t1); | |
alloc.free(self.t2); | |
} | |
}; | |
pub fn main() !void { | |
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; | |
defer std.debug.assert(!general_purpose_allocator.deinit()); | |
const gpa = general_purpose_allocator.allocator(); | |
var rest_struct = try ResStruct.init(gpa, "testme123"); | |
defer rest_struct.deinit(gpa); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment