4 ms·
> This is unavoidable in any language that (supports dynamic memory allocation and) moves dynamic memory allocation into a library. Not necessarily. The Zig[1
by messe 4y ago
> This is unavoidable in any language that (supports dynamic memory allocation and) moves dynamic memory allocation into a library.
Not necessarily. The Zig[1] standard library forces callers to provide at runtime an allocator to each data structure or function that allocates. Freeing is then handled either by calling .deinit()—a member function of the datastructure returned (a standard convention)—or, if the function returns a pointer, using the same allocator you passed in to free the returned buffer. C's problem here is it doesn't have namespaces or member functions, so there's a mix of conventions for what the freeing function should be called.
C++ allows this as well for standard library containers, although I've rarely seen it used.
> Also, say a DLL function returns a char pointer containing a string. How would you know whether to call free or delete on it? Or, maybe, the equivalent of free in Frob, the language that DLL happens to be written in?
I have to concede this one. I can't see a way out of this other than documentation.
[1]: https://ziglang.org/ https://ziglang.org/
- nine_k 4y agoYou provide a memory allocation interface either way: it may be a special function per type, it may be a generic allocator.
- thechao 4y agoIf `push_back()` & friends took an (optional) extra allocator parameter, it'd be pretty ideal. It'd be nicer if the implementations were forced to be single-word containers like Stepanov wanted...
- messe 4y agostd::vector can take an allocator as a template parameter though? For a list, sure I can see that having a separate allocator per element could work, but for a vector, surely you'd want the same allocator for the entire range? EDIT: assuming we're talking about C++, if not please don't hesitate to corrrect me.
- thechao 4y agoStateful allocators require a word be dedicated to the allocator in the header. In my use cases, I always have access to the allocator, but I need to create a lot of containers — most staying empty, to boot! Paying the extra overhead is morally objectionable.
- messe 4y agoC++ might have the advantage here then: it's a template parameter, in other words, the allocator is decided at compile-time, meaning that no additional storage space would be needed if you know in advance which allocator you intend on using.