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

Maybe I just suck at reading, but I'm not sure I get the argument for why function overloading and constructors are required for RAII. Is it some interaction with C and C++'s object models that I clearly didn't understand?


Me attempting to summarize the article:

There are 2 ways to get C++-style RAII into C. The first way is to wholesale import the C++ object system into C (which means name mangling, all the different flavors of constructors, destructors, etc). Conceptually this would work, but it's never going to happen, because implementing that would be literally more work than an entire conforming C99 compiler.

The second way is to just use some special function attributes to signify that a function runs when an object is created on the stack / popped off the stack. This won't work either because the C++ object system also solves lots of other problems that this simpler system just ignores (such as, what happens when you copy an object that has a constructor function).


The C language has rules around 'effective type' which determine what object type a block of memory can have, while the C++ language has rules around object model which does basically this AND requires that a constructor is called on an object before it is properly regarded as being of that object type. In my opinion the reason why the C++ standard cares about object lifetime is because C++ structs can have reference members which are required to be initialized in any instance of that struct type. In contrast it's compatible with what C has of an object model to just say to language users "If an object is in static or automatic storage the constructor is called automatically but if an object is in heap storage it's up to the user to call the constructor themselves."

amateur C++ coder


Ah, I missed the "copy wholesale" aspect.

When I started reading it, the first thing that came to my mind was the issue with copying the structs. The article started looking at the issue, but didn't really follow further with the changes needed to make it work, which is that you start needing to introduce tracking which instance is responsible for the resources and providing a way to transfer that responsibility (a.k.a. ownership and move semantics).


Nah the first half of the essay is basically irrelevant, you need to start below that, and what I consider the meat of the issue is the “copy” section about two thirds down.




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

Search: