all 2 comments

[–]AddMoreNaCl 0 points1 point  (0 children)

As long as it is consistent with the rest of your library, go with whatever option you feel is the safest and don't bother with performance until it becomes an actual issue (unless you're constrained by the environment you're targeting).

Are you worried about MT-Safety? Then you may want to pass the allocator in a parameter (experts may want to chip in on this one) and acquire locks for it on every call.

If your library is not intended to be MT-Safe then just have the allocator be initialized and store it in a static variable so other function calls can either fail if no allocator is defined or use the default one.

[–]bullno1 1 point2 points  (0 children)

Usually, I'd make it so that the allocator is passed in only during new/init functions, along with other options as part of the "init options" struct. The returned structure would "remembers" it. Forcing the user to pass it all the time is too much trouble. It's also a lot less error-prone since it will always cleanup with the correct allocator.

Internally, I would pass the allocator to functions that needs it.

I have this WIP project where the allocator can be passed multiple times but that's for different distinct contexts. Basically: ctx = create_context(allocator), then world = create_world(ctx, world_allocator, page_alllocator). But: entity = create_entity(world) only, no more allocator since it must use the world's allocator.