3 ms·
>I cannot count how many times I saw C libraries forcing you to use reference-counted objects on the heap just to get out of the messy they used pointers. That
by cycloptic 6y ago
>I cannot count how many times I saw C libraries forcing you to use reference-counted objects on the heap just to get out of the messy they used pointers.
That's because this is by far the easiest way to implement Pimpl and allow for safe bindings to higher level languages at the same time. For libraries aimed at high-level usage patterns there simply is no reason to bother supporting other allocation strategies, especially when the library itself needs to call malloc internally anyway.
Often I do actually see low-level C libraries using this pattern:
struct obj {
/* expose your private fields here */
};
void obj_init(struct obj *);
void obj_cleanup(struct obj *);
Where the calling code can allocate the object however it wants, but this won't work for any libraries that want to maintain ABI compatibility between versions.
- qalmakka 6y agoNot having any control on how a library allocates memory is a huge downside, though, and it's something C++ has in my experience largely resolved (at the expense of ABI compatibility, which is something that IMHO hasn't hindered its adoption that much). Not being able of using stack for short lived objects is also pretty bad for performance, especially if the allocation/deallocation is done in a cycle. I understand the desire of maintaining a stable ABI, but I think this should be optional and at the discretion of the user instead of being shoved down as the only way to use a library. At least, I think such libraries should allow their users to overload whatever malloc/free the library is supposed to use, even though it's less than ideal.