Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yes, it meanders to much to get to the point. Which is that RAII doesn't work in C because unlike C++, which has a comprehensive type system mandated by a standard, a C program doesn't "know" at runtime that a struct is composed of other (typed) fields so it can do a proper deep field copy (or destruction). And implementing that type system in C doesn't seem feasible for practical and political reasons.

I think the actual question should be "can C get automatic memory management like in C++ without having the equivalent of C++'s type system"?

Though I can't put my finger on it, my intuition says it can, if the interested people are willing to look deep enough.



> a C program doesn't "know" at runtime that a struct is composed of other (typed) fields so it can do a proper deep field copy (or destruction).

This doesn’t make sense: you don’t need runtime introspection to do this?


In C++, when you copy a struct instance to another instance, the runtime knows if any fields (to whatever depth) have manually defined assignment or move operators and will call them in the proper order. So it's a deep copy. The same information is used for calling any field constructors and destructors that are user defined.

Introspection (reflection) would go even further and provide at runtime all the information that you have at compile time about an object. But that's not required for assignment and destruction operations to work.

C doesn't have any of that, so a struct copy is just a shallow copy, a bit by bit copy of the entire struct contents. Which works pretty well, except for pointers/references.


No. Well, yes, in that if the type of an object is dynamic, it's possible that certain functions are resolved at runtime usually through a "virtual table". The static type of an object is only known at compile time, and all that the virtual dispatch does is an indirection through the virtual table to the static constructor or destructor as required, and the static special functions always know how to construct, copy, or destroy any subobjects.

So, no, runtime introspection is not needed, but runtime dispatch may be needed.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: