12 ms·
Why not just do simple C++ RAII in C?
- slaymaker1907 2y agoI'd argue it barely works in C++ as well. I've seen so many poorly implemented classes that violate the very complicated 3/5/0 rule. It's much easier to do RAII correctly in Rust since people aren't constantly working with raw pointers and since objects which are moved somewhere else are not dropped like they are in C++. One variant that I think might work even better than RAII or defer in a lot of languages is having a thread local "context" which you attach all cleanup actions to. It even works in C, you just define cleanup as a list of typedef void(cleanup_function*)(void* context); which is saved as into a thread local. Unlike RAII, you don't need to create a custom type for every cleanup action and unlike the call-with pattern from functional programming, lifetimes of these lists can be non-hierarchical. However, I'm still glad to see defer being considered for C. It's a lot better than using goto for cleanup.
- pavlov 2y ago> 'a thread local "context" which you attach all cleanup actions to' Like the autorelease pool found in Objective-C of yore? I always liked that solution and sometimes implemented in plain C too.
- adrianN 2y agoYeah, the example of "what if you make a copy" breaks in C++ in exactly the same way if you're not careful.
- d0mine 2y agoArena can be used to allocate many times but deallocate exactly once. In Zig: test "arena allocator" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); _ = try allocator.alloc(u8, 1); _ = try allocator.alloc(u8, 10); _ = try allocator.alloc(u8, 100); }
- jay-barronville 2y agoI’m a fan of Zig, but I just want to point out that creating dedicated allocators for managing specific regions/chunks of memory or memory within specific application scopes (i.e., arenas) is just another memory allocation strategy rather than the ultimate solution to memory management issues. It comes with its own trade-offs and depends entirely on your use case. Also, it’s great that Zig has this battery included in its standard library, but arenas aren’t unique to Zig nor are they difficult to implement in any language that allows manual memory management. I’m just pointing this out because I keep seeing folks highlight this as a key feature of Zig over C.
- anymouse123456 2y agoThis. I've been loving Zig for some years now, but still write a lot of embedded C at work. I've started to use simple memory arenas in C and it just feels so damn _nice_. There's basically a shared lifetime for most of my transient allocations, which are nicely bounded in time by a "frame" of execution. Malloc/Free felt like a crazy amount of work, whereas an arena_reset(&ctx) just moves a pointer back to the first entry. Another person pointed out that arenas are not destructors, and this is a great point to make. If you're dealing with external resources, moving an arena index back to the beginning does not help - at all.
- OskarS 2y agoYou can do it in C for sure, but "culturally" in C, there's a stateless global allocator called "malloc", which is not the case in Zig. For instance, if you have a library libsomething in C, it will at most (probably) have something like this: #ifndef LIB_MALLOC #define LIB_MALLOC malloc #end if it allows you to customize allocation strategy at all, which is not a given. But this only allows you at compile time to provide your own stateless global allocator. This is very different in Zig, which has a very strong culture of "if something needs to allocate memory, you pass it a stateful, dynamically dispatched allocator as an argument". You COULD do that in C, but virtually nobody does.
- samatman 2y agoIt's 100% a key feature of Zig. Culturally, if it allocates, then it takes an allocator as an argument. C simply doesn't work that way. You could write C that way, but people don't. I've written reasonable amounts of both, and it's just different. For instance, in Zig, you can create a HashMap using a FixedBufferAllocator, which is a region of memory (which can be stack allocated) dressed up as an allocator. You can also pass it an arena and free all at once, or any other allocator in the standard library, or implemented by you, or anyone else. Show me a C library with a HashMap which can do all three of these things. Everything which allocates takes an allocator, third-party libraries respect this convention or will quickly get an issue or PR either requesting or implementing this convention. Ultimate solution? No, but also, sort of. The ability to idiomatically build a fine-grained memory policy is a large portion of what makes Zig so pleasant to use.
- Gibbon1 2y agoMy small brained comment is people use heap allocation when they should be using an arena allocation. And heap allocation shouldn't return a pointer it should return a handle.
- vlovich123 2y ago> that violate the very complicated 3/5/0 rule Is it actually complicated? There’s only the rule of 0 - either your class isn’t managing resources directly & has none of the 5 default methods defined explicitly (destructor, copy constructor/assignment, move constructor/assingment), or it manages 1 and exactly 1 resource and defines all 5. Following that simple rule gives you exception safety & perfect RAII behavior. Of all the things in C++, it seemed like the most straightforward rule to follow mechanically. BTW, the rule of 3 is from pre-C++11 - the addition of move construct/move assignment makes it the rule of 5 which basically says if you define any of those default ones you must define all of them. But the rule of 0 is far stronger in that it gives you prescriptive mechanical rules to follow for resource management. It’s much easier to do RAII correctly in Rust because of the ecosystem of the language + certain language features that make it more ergonomic (e.g. Borrow/AsRef/Deref) + some ownership guarantees around moves unless you make the type trivially copyable which won’t be the case when you own a resource.
- chipdart 2y ago> Is it actually complicated? It is. There is no point in arguing otherwise. To understand the problem, you need to understand why it is also a solution to much bigger problems. C++ started as C with classes, and by design aimed at being perfectly compatible with C. But you want to improve developer experience, and bring to the table major architectural traits such as RAII. This in turn meant you add support for custom constructors, and customize how your instances are copied and destroyed. But you also want to be able to have everything just work out of the box without forcing developers to write boilerplate code. So you come up with the concept of special member functions which are automatically added by the compiler if they are trivial. However, forcing that upon every single situation can cause problems, so you have to come up with a strategy that suits all use cases and prevents serious bugs. Consequently, you add a bunch of rules which boil down to a) if the class/struct is trivial them compilers simply add trivial definitions of all special member functions s that you don't have to, but once you define any of those special member functions yourself them the compiler steps back and let's you do all the work. Then C++ introduced move semantics. This refreshes the same problem as before. You need to retain compatibility with C, and you need to avoid boilerplate code, and on top of that you need to support all cases that originated the need for C++'s special member functions. But now you need to support move constructors and move assignment operators. Again, it's fine if the compiler adds those automatically if it's a trivial class/struct, but if the class has custom constructors and destructors then surely you also need to handle moves in a special way, so the compiler steps back and lets you do all the work. On top of that, you add the fact that if you need custom code to copy your objects around, surely you need custom code to move them too, and thus the compiler steps back to let you do all the work. On top of this, there are also some specific combinations of custom constructors/destructors/copy constructors/copy assignment operators which let the compiler define move constructors/move assignment operators. It all makes absolutely sense if you are mindful of the design requirements. But if you just start to onboard onto C++ and barely know what a copy constructors is, all these aspects are arcane and sadistic. If you declare nothing then your class instances are copied and moved automatically, but once you add a constructor everything suddenly blows up and your code doesn't even compile anymore. You spotted a bug where an instance of a child class isn't being destroyed properly, and once you add a virtual destructor you suddenly have an unrelated function call throw compiler errors. You add a snazzy copy constructor that's very performant and your performance tests suddenly start to blow up because of the performance hit if suddenly having to copy all instances instead of the compiler simply moving them. How do you sort out this nonsense? The rule of 5 is a nice rule of thumb to allow developers to have a simple mental model over what they need to do to avoid a long list of issues, but you still have no control over what you're doing. Things work, but work by sheer coincidence.
- bluGill 2y agoI've never seen someone get the rule of 5 wrong, but the rule of 3 was a reaction to 10 years of hindsight to realise the default is wrong. Congradulations to rust for looking to see what was done wrong by their predisessors. you can't really fault someone for making a mistake when nobody at the time knew it was a mistake.
- chipdart 2y ago> I'd argue it barely works in C++ as well. I've seen so many poorly implemented classes that violate the very complicated 3/5/0 rule. I'm afraid you're complaining about entirely unrelated things. It's one thing to claim that C++ structs have this or that trait. It's a entirely different thing to try to pin bugs and developer mistakes on how a language is designed.
- rramadass 2y ago> the very complicated 3/5/0 rule It is not very complicated at all; just a discipline to follow (or not if you know what you are doing) once learnt - https://en.cppreference.com/w/cpp/language/rule_of_three https://en.cppreference.com/w/cpp/language/rule_of_three Incidentally i use it as 4/6/0 by including the default ctor in the set.
- deleted 2y ago[deleted]
- uecker 2y agoI was initially interested in defer in C (I am co-author of some earlier proposal), but after actually studying its impact on code example I was entirely unimpressed about the actual improvement compared to goto style cleanup. A lot of people seem to like it though, and JeanHeyd's version seems quite good, but I personally not terribly convinced about this feature anymore.
- gary_0 2y agoIn other words, C structs and C++ structs are not the same thing (although C++ can usually handle C structs too). C structs are Plain Old Data. C++ structs are "objects" and there are pages and pages of rules in the C++ Standard about what that means, and there's no way the C Standard can incorporate all that. And you can't drag any C++ struct/class features into C without dragging in all those rules with them.
- stonemetal12 2y agoYep. The only difference between struct and class in C++ is that class defaults to private while struct defaults to public. 100% of the using structs like they are C structs vs using class as objects is cultural not a part of the language.
- SAHChandler 2y agoThe public vs. private aspect also affects inheritance. structs publicly inherit from base types by default, classes privately inherit from base types.
- gary_0 2y agoAny similarly of keyword naming between C and C++ is purely coincidental. :P C++ is somewhat unique in that it started out as a few extra features on top of C before gradually splitting off and mutating into a totally separate programming language.
- pjmlp 2y ago"Unique" in a world where Objective-C, Objective-C++, Groovy, and TypeScript exist.
- gary_0 2y agoWhat I meant wasn't that it was a language that was compatible with an earlier language. Groovy just compiles to the JVM; lots of things do. TypeScript is just JavaScript with type safety; Python did that too. Objective-C was just NeXT attempting to make the ugliest-looking programming language possible and they succeeded immediately. But Cfront was released circa 1983 and you basically just wrote C, but it added a bit of new syntax that generated extra C behind the scenes. Object-oriented programming was still fetal in 1983! It didn't get really hyped until the mid-90's. So C++ kind of mutated for decades as this gross appendage on C until it became this whole separate blob that ate half of programming. It was 15 years later when the C++98 "standard" started trying to reign in Dr. Stroustrup's monster. Then in 2005 we threw away all our textbooks that were like "Look! `Apple` derives from `Fruit`! `Car` derives from `Engine`! This is going to change the world!" because adding object-orientedness to everything became uncool when our bosses became fans of Java. But by this point the C++ blob had taken on a life of its own... So yeah. Very few programming languages have a story as long and insane as C++.
- eschneider 2y agoIt would seem that if you want C with RAII, you...use C++ and limit the features you use. QED.
- manuel_w 2y agoSounds reasonable. In a project I used to work in I disabled stdlib, exceptions, RTTI. Not sure what else to disable to essentially have C with different syntax.
- legobmw99 2y agoextern “C” on everything, if you care about linking compatibility, gets you another chunk of the way there by also disabling overloading etc.
- 01100011 2y agoThis is surprisingly common. C++ is huge and filled with many features that are only understood by a small subset of folks and so many teams have restricted coding standards that define which features can be used and how.
- wrs 2y ago>The utterly pervasive and constant feeling that a lot of people – way too many people – are really trying to invent these things from first principles and pretend like they were the first people to ever conceive of these ideas… it feels pretty miserable, all things considered. Going through life evaluating effectively no prior art in other languages, domains, C codebases as they exist today, just… anything. Oh man, I hear ya. And in a lot more domains than computer language design. Is it inexperience? Impatience? The tendency for search results to be filled with low-quality and high-recency content? The prioritization of hot-take blog posts and Reddit comments over books?
- lpapez 2y agoI kind of emphatize with the author raging at "just copy C++ bro" proposals because at $TWO_JOBS_AGO I had to deal with an "Architecture Team" full of Very Senior(tm) people who would show up uninvited and give advice like "did you know you can pee and poo at the same time?" Of course, but if you bothered at all to understand the constraints, you would have seen it is not actually that simple in our case. And my project was several orders of magnitude simpler than the C standard.
- phendrenad2 2y agoI feel like this is an archetype. Show up out of nowhere, half-understand the problem, make a brain-dead suggestion, and then as soon as you point out the problems with that approach, they're suddenly too busy with other things to respond.
- meindnoch 2y agoArchitect: you know, I just feel like there should be a way to solve this in a proper way Engineer (thinking): (No, you idiot, there isn't, because it's broken! I told you, all options have been tried, and this was the least painful way of doing it. Yes, it's not the ideal solution, but there's no other way, unless the upstream vendor decides to fix the issue on their end!) Engineer: thanks, I'll look into it :)
- deleted 2y ago[deleted]
- xmodem 2y agoI had one where the architecture team implemented the brain-dead solution, advised leadership of other teams that they should adopt the brain-dead solution, and that my team would be supporting the brain-dead solution, without consulting us, and made me into the bad guy when I pointed out that my team did not support the brain-dead solution. We ended up supporting the brain-dead solution, but that team has now experienced 100% turn over since then.
- chipdart 2y ago> (...) I had to deal with an "Architecture Team" full of Very Senior(tm) people who would show up uninvited and give advice like "did you know you can pee and poo at the same time?" It reads like you had experts giving you advise on how to improve things, and instead not only did you ignored their advise but you went to the extent of mindlessly disparaging their help.
- Xeamek 2y agoIs RAII even wanted? I mean, in the name, 'Resource acquisition is initialization' it talks about the initialization part. But while not super versed in cpp, it looks like what everybody wants is actually the de-initialization part, which doesn't seem to be inherent to RAII, no? It's a bit confusing to have a 'thing' mention one mechanism in its name, but actually being valuable by ensuring some other mechanism
- legobmw99 2y agoI feel like most RAII fans will openly admit that it’s the worst name in the world for such an idea. The idea is that any time you acquire a resource, you should initialize an object with said resource. But I guess “resource allocation should always lead to object initialization” is too long. The reason to do this is precisely so that the resource can be cleaned up at destruction of the object. So even if you had an acronym like RASALTOI, it would still probably be misleading
- NekkoDroid 2y agoRAII is the worst name they could have selected and C++ devs openly admit that. Its more SBRM, Scope Based Resource Management.
- susam 2y ago> It's a bit confusing to have a 'thing' mention one mechanism in its name, but actually being valuable by ensuring some other mechanism. Indeed! When I was first learning C++, I found the term "RAII" quite confusing too. However, after years of experience with this term, associating "RAII" with its intended meaning has become second nature. Having said that, there is at least one way to make better sense of "RAII" and that is considering the fact that in RAII, holding a resource is a class invariant. The resource is acquired during construction (initialisation) and released during destruction (which happens automatically when the object of the class goes out of scope). Throughout the object's lifetime, from construction to destruction, maintaining possession of the acquired resource is an invariant condition. Although sounds simple in principle, this can get complicated pretty quickly, especially in the implementation of the copy assignment operator where we may need to carefully delete an existing resource before copying the new resource received by the operator. Problems like this led to formulating more techniques for carefully managing the resources while satisfying the class invariant. One such technique is the copy-and-swap idiom. None of this is meant to justify the somewhat arbitrary term though. In fact, there are at least two better alternative names for RAII: Scope-Based Resource Management (SBRM) and Constructor Acquires, Destructor Releases (CADR).
- jokoon 2y agoI wish there was some way that you could configure a C++ compiler to just disable certain features of the language, or enforce good practices. But that's already what linters/static analyzers are doing? But then, why not integrate those tools directly in a C++ compiler instead? With cpp2/cppfront, Herb Sutter is already building some sort of a "sane" subset of the C++ language, maybe because you cannot achieve good practices without having a new syntax. C++ seems to have the same problem of javascript: it has annoying "don't-do-that" use cases, although it seems insanely more complicated to teach good C++ practices.
- fweimer 2y agoYou can write a compiler plugin that rejects constructs you don't like. Even GCC doesn't immediately lower the more complex (more controversial) C++ constructs. There's an existing system headers mechanism, so it's probably not that hard to skip this kind of feature restrictions for the standard library headers (where the banned constructs might be used to implement something that looks completely different at the surface).
- ThatGeoGuy 2y agoThis is more or less what Sean Baxter was trying to do with https://www.circle-lang.org/ https://www.circle-lang.org/. Of course, this requires buying into a set of tooling and learning a lot of specific idioms. I can't say I've used it, but from reading the docs it seems sound enough.
- pjmlp 2y agoThat is what static analysers are for. The issue is developers that think they are useless tools.
- mst 2y agoUsefully albeit depressingly, these days you can often get significantly easier buy-in if you call it a linter instead.
- sixfiveotwo 2y ago[dead]
- jay-barronville 2y agoC is the ultimate WYSIWYG language (provided you understand the semantics of your target architecture and assuming a non-buggy compiler). The language is relatively simple. The standard is accessible. I’d like it to remain that way. I don’t need C to adopt any other “modern” language features. C11 provided a few worthwhile improvements (i.e., a proper memory model, alignment specification, standardized anonymous structures/unions), but so many of the other additions, suggestions, and proposals I’ve seen will just ruin the minimal nature of C. In C++, a simple statement like `a = b++;` can mean multiple constructors being called, hidden allocations, unexpected exceptions, unclear object hierarchies, an overloaded `++`, an overloaded `=`, etc. Every time I wish I had some C++ feature in C, I just think about the cognitive overhead it’d bring with it, slap myself a couple times, and go back to loving simple ole C. Please don’t ruin C.
- chowells 2y agoAnd presuming you avoid 100% of undefined behavior, which I've never seen a non-trivial C program succeed at. C is way too complicated in the real world. You don't want C, you want a language that actually gives defined semantics to all combinations of language constructs.
- einpoklum 2y agoYou don't necessarily want that. Forcing language-defined semantics on everything costs performance. Sorry, it just does, we can't have it all. So, you can sacrifice performance for well-defined'ness, or you can choose not to - and the choice depends on the language _design goals_. As the design goals differ, so do the combinations of choices made for syntax and semantics.
- bigstrat2003 2y agoI think pretty much any amount of performance is worth sacrificing in order to get rid of the gnarly things UB can cause. Correctness is the first and most important thing in programming, because if you can't be certain it works then it's not very useful.
- pornel 2y ago> “just ban simple automatic storage duration structure copying” is a terrible usability and horrific ergonomics decision to make This sounds like a great idea to me! Rust disables implicit copying for structs with destructors, and together with move-by-default, it works really well. Unlike PoD structs, you don't need to heap allocate them to ensure their uniqueness. Unlike copy constructors, you don't need to worry about implicit copies. Unlike C++ move, there's no moved-from junk value left behind.
- meinersbur 2y agoIMHO it would still be a useful feature, just one that is not strictly needed. You are not able to to pass around such structs, but neither is that possible with the suggested `defer` statement. The only advantage of `defer` is that the destructor code is inline, rather than in a separate destructor function. But you could gain reusability of headers to be also used in C++, not needing to reinvent the wheel with new issues (e.g. variable lifetime), and a whole lot of existing experience with RAII.
- tialaramex 2y ago> Rust disables implicit copying for structs with destructors "Disabling" is maybe not the right way to think about it. Rust only has "implicit copying" for Copy types, so you have to at the very least #[derive(Copy,Clone)] to get this, it's true that you can't (and therefore neither can a derive macro) impl Copy on types which implement Drop and that's on purpose but you're making a concrete decision here - the answer Rust knows is never correct is something you'd have to ask for specifically, so when you ask it can say "No" and explain why. Lots of similar behaviour in C++ is silent. Why isn't my Doodad behaving the way I expected? I didn't need to ask for it to have the behaviour I expected but the compiler concludes it can't have that behaviour, so, it doesn't, and there's nowhere for a diagnostic which says "Um, no a Doodad doesn't work like that, and here's why!" Diagnostics are hard and C++ under-values the importance of good diagnostics. Rust recently landed work so libraries can provide improved diagnostics when you try to call them with inappropriate parameters. For example now if you try to collect() an iterator into a slice, the compiler notices that slice doesn't implement FromIterator and it asks FromIterator to explain why this can't work, whereupon FromIterator notices you were trying to use a slice and emits a diagnostic for this particular situation - if you'd tried to collect into an array it explains how you'd actually do that, since it's tricky - the slice is impossible since it's not an owning type, you need to collect into a container.
- potbelly83 2y agoI'm confused why are they trying to implement name mangling in C? Are they trying to use the C++ compiler to implement the RAII assembly code and then link that back into C? Wouldn't a smarter approach be to do a C version of what C++ does?
- jay-barronville 2y agoI thought the author covered that pretty well. How would you make sure that function calls and object lifetimes are managed correctly/deterministically while also remaining compatible with existing C++ code and compilers without having to have `extern "C"` everywhere? Edit: I just reread this comment and realized the beginning of it could come across as a bit condescending even though that wasn’t at all my intention. I’d edit it out, but I don’t like doing that, so my apologies if it did come across that way!
- nicebyte 2y agothey're not. they're saying "if we had constructors in c, we'd need a mechanism to allow multiple constructors for the same type". in c++ function overloading and mangling are used to get that, but it's far from the only way something like that could be achieved. imo that whole part could be removed, it's like a little distraction and doesn't really have anything to do with the core of their argument.
- potbelly83 2y agothanks! appreciate the reply
- einpoklum 2y agoA C++ code design note: The initial example in the article is anti-idiomatic, because it imbues the larger class with a RAIIness which can be limited to just one element of it: struct ObjectType { int a; double b; void* c; ObjectType() : a(1), b(2.2), c(malloc(30)) { } ~ObjectType() { free(c); } }; It's only the c member that really requires any special attention. In this particular case. So, there should be something like a `class void_buffer` which is a RAII class, and then: struct ObjectType { int a; double b; void_buffer c; ObjectType() : a(1), b(2.2), c(30) { } }; and actually, let's just not sully the set of constructors, but rather have: struct ObjectType { int a; double b; void_buffer c; static ObjectType make() { return ObjectType{ 1, 2.2, 30 }; } }; and now instead of a complicated bespoke class we have the simplest of structs; the only complexity is in void_buffer.
- nottorp 2y agoYes, that's a property of C++. It tempts you to hide complexity under several layers of classes so you can have ... more classes, i guess? And job security, because it makes the code much harder to follow for whoever didn't write it.
- daemin 2y agoIn this case it's not complexity but a useful abstraction. It abstracts the void_buffer into its own type with proper correct functions for creating, (maybe copying), moving, and destructing the buffer. With that you get a simple type that you can use elsewhere without needing to remember that you need to free() the buffer manually before the end of the scope, or needing to remember how to correctly copy or move the buffer elsewhere.
- einpoklum 2y ago"More classes" is not something detrimental in any way, in itself. You can have "more classes" while also having: * Less code overall * More reuse of classes as versatile/simple components, as opposed to a zoo of bespoke classes * Classes which are simpler to understand and with more predictable behavior This is true in the example above: With the corrected code, it's enough that I tell you "ObjectType is a simple struct; and one of its members is a buffer of untyped data". I don't have to show you the class definition; you know enough to understand what's going on. And you can use your void_buffer elsewhere.
- nicebyte 2y agoI respect Jean-Heyd very much, but I'm unconvinced by this article. First, the whole name mangling discussion is completely irrelevant to the issue and can be omitted. Second, one could tack on both copy and move constructors on to C in order to solve the double-free issue, in much the same way regular ctors are tacked on in the email proposal. In fact, I would argue that it is _necessary_ because A in RAII stands for Acquisition not Allocation. "Acquisition" implies ownership, which can be transferred or shared, so your copies and moves _have_ to have a special meaning to them. The fact that the proposal is bad or incomplete does not mean that it is "impossible" to have RAII in C. I don't claim that it _is_, but reading this did not reveal to me anything fundamental that would preclude RAII, only that all the preceding RAII proposals have been sloppy.
- scott_s 2y agoI found the arguments compelling. The discussion on "Effective types" and C not having a proper concept of objects is key. Another way to think about it: even if you had defined constructors and destructors for a struct, you have not solved when to call them. C++'s answer to that question is its sophisticated object model. C does not have one, and in order to answer that question, it must. It's worth noting that RAII was not a feature that was intentionally created in C++. Rather, astute early C++ developers realized it was a useful idiom made possible by C++'s object model.
- indigoabstract 2y agoYes, 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.
- orf 2y ago
- Measter 2y agoMaybe 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?
- defen 2y agoMe 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).
- Measter 2y agoAh, 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).
- jacinabox 2y agoThe 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
- wakawaka28 2y agoBecause you can just use actual C++ lol...
- lionkor 2y agoC has scopes. Add destructors. That's pretty much all you need to get most of the benefits of RAII. You can add `defer` instead, but regardless, this has nothing to do with C++. You can implement safety features without having to copy the arguably worst language in the world, C++. I like C++, I wrote many larger projects in it, but it sucks to the very core. Just add RAII to C.
- leduyquang753 2y agoDid you even read the article? The part where it talks about problems with destructors is about halfway through.
- lionkor 2y agoThey assume C++-like destructors. Other languages, like Zig, do a good job with syntax like `defer`
- masklinn 2y agoThey don’t “assume” C++-like destructor, they’re the primary author of the N3199 “defer” proposal for C. This is a response to people contacting / criticising them asking for destructors instead of defer.
- jcranmer 2y agoThe entire point of the blog post (written by the author of the C defer proposal) is to motivate why C should have defer. It is an attempt to summarize one of the most common criticisms of the proposal.
- masklinn 2y agoTBF the essay is rather strangely structured, the entire two thirds of the essay covering constructors and overloading has only ancillary relevance to the actual problem, Rust has neither and does RAII just fine after all (though it does have name mangling). The author even acknowledges halfway through that it’s basically a strawman: > It’s not a bad argument; after all, the entire above argument hinges on the idea of stealing from C++ entirely and copying their semantics bit-for-bit. To me, only after that does it engage with the underlying concept in a way which is engaging and convincing. But you’ve had to trawl through 2500 words to get to that point.
- guillaumec 2y agoI notice more and more pushes to 'improve' C and turn it into something it should not become. I feel like the C++ community gave up on C++ because of the growing complexity and so turned to C with the hope of adding to it the good parts of C++ without the ugliness. But this is of course hopeless: every added feature will create new issues that will be solved with new features until the language becomes too complex for anyone to fully understand.
- fch42 2y agoThe part in it that I don't understand is ... Again, "traditionally", one could (ab)use C++ as "C with extras". And it wasn't uncommon, especially in resource constraint usecases, to do just that. C++ without STL or templates, or even C++ without new/delete. This "is not C++", agree. Would a subset be enough for "using it like C-with-RAII" ? Given the details and pitfalls the original author lists, I suspect not. It's not just C programmers who "do strange things" and make odd choices. The language itself though "lends itself to that". I've (had to) write code that sometimes-alloca'ed sometimes-malloc'ed the same thing and then "tagged" it to indicate whether it needed free() or "just" the implied drop. Another rather common antipattern is "generic embedded payloads" - the struct definition ending "char data[1]" just to be padded out by whatever creates it to whatever size (nevermind type) of that data. Can you write _new_ C code that "does RAII" ? Probably. Just rewrite it in rust, or zig :-) Can you somehow transmogrify language, compiler, standard lib so that you can recompile existing C code, it not to "just get RAII" then at least to give you meaningful compiler errors/warnings that tell you how to change it ? I won't put money on that.
- actionfromafar 2y agoNew/delete were never that great to begin with and have now fallen out of style. Also, C++ is quite useful and powerful even without STL. https://www.youtube.com/watch?v=rX0ItVEVjHc https://www.youtube.com/watch?v=rX0ItVEVjHc A classic which touches on such stuff.
- bluetomcat 2y ago> Can you write _new_ C code that "does RAII" ? Probably. You can do "manual" goto-based RAII in C, and it has been done for decades. The end of your function needs to have a cascading layer of labels, undoing what has been done before: if (!(x = create_x())) { goto cleanup; } if (!(y = create_y())) { goto cleanup_x; } if (!(z = create_z())) { goto cleanup_y; } do_something(x, y, z); cleanup_z: destroy_z(z); cleanup_y: destroy_y(y); cleanup_x: destroy_x(x); cleanup: return; It just takes more discipline and is more error-prone maintenance-wise.
- julian_t 2y agoIs there a law, like Betteridge's Law, that says "the answer to any question that says 'why not just' is 'it isn't as simple as that'"?
- iainmerrick 2y agoThis is obviously a bit of a rant, and intended as such, but it’s really well thought through and well-argued too. I haven’t seen this distinction laid out so clearly before: Every other language worth being so much as spit on either employs deep garbage collection (Go, D, Java, Lua, C#, etc.) or automatic reference counting (Objective-C, Objective-C++, Swift, etc.), uses RAII (Rust with Drop, C++, etc.), or does absolutely nothing while saying to Go Fuck Yourself™ and kicking the developer in the shins for good measure (C, etc.). GC, ARC, RAII or GTFO, those are the options. That’s right! I always come away from these discussions with more respect for Objective-C -- such a powerful yet simple language. I suppose Swift is the successor but it feels very different. Although, Obj-C only really came into its own once it finally gained automatic reference counting, after briefly flirting with GC. At that point it was already being displaced by younger and more fashionable languages.
- OskarS 2y agoI would say there are two more esoteric options: "no memory allocation at all outside of the program stack" (like... i dunno... lambda calculus?) and fancy-pants computer sciency things like linear types. No sane language does either of those, though.
- iainmerrick 2y agoGood points! I tend to think of linear types as a more general kind of RAII -- like there's a spectrum that goes RAII -> borrow checker -> linear types -- but maybe it does warrant its own category.
- yason 2y agoRAII is just automation and semantic sugar for something like this (or the equivalent set of goto labels that do the freeing at the end of the function): { void *buffer = malloc(SIZE_MAX); if (buffer) { if (!do_stuff(buffer)) { free(buffer); return; } more_stuff(buffer); free(buffer); } return; } If you wanted something like that in C it doesn't need to emulate C++ style RAII with classes and strongly typed constructors. It could look like something like, for example, where you just define pairs of allocator and free functions: allocdef void *autobuffer(malloc, free); ... { autobuffer buffer(SIZE_MAX); if (buffer) { if (do_stuff(buffer)) { return; } more_stuff(buffer); } return; } The implementation would effectively be a Lisp style macro expansion encoded in the C compiler (or preprocessor) that would just basically write out the equivalent of the first listing above.
- Mesopropithecus 2y agoIn the second example, buffer is still a pointer? If so, when does free run, and who decides that? When buffer goes out of scope, could do_stuff store the pointer some place else? I find this an interesting thought experiment, basically types that you'd opt in to RAII. Just have a feeling that you'll need to define some notion of ownership to make it work.
- kalekold 2y agoUse D's -betterC flag? https://dlang.org/spec/betterc.html https://dlang.org/spec/betterc.html
- ezoe 2y agoI really don't understand why the author is so mad at these armchair professionals who think they know better. You are proposing to change the C language. The risk is great even the smallest change will break the existing code. If you can't convince all of the stakeholders, it's better not to change it. Keep the status-quo.
- wizzwizz4 2y agoYou underestimate the sheer diversity of existing C compilers. A specification change is not a significant risk to existing code, compared to even clang v.s. gcc compatibility issues.
- rqtwteye 2y agoI always find it interesting to see calls to mallow and free in C++ code. I don't recall using malloc/free in many years in C++. It's always new/delete.
- PaulDavisThe1st 2y agoIf you're reading these comments (and maybe contributing to them) about various arcane details of C++ and the differences with C, there's one thing you're not doing ... ... actually writing code that gets the job done ... in C++.
- deleted 2y ago[deleted]
- throwawaymaths 2y agoHow about instead of RAII built into the compiler, you define destructor functions for each datatypes that you care to and have a sidecar or compiler plugin or hell even a linter check that those destructors have been called when a variable of that type goes out of scope? If you miss a destructor event, without configuring the addon "yes I really meant that", the addon halts the compilatoin at best, or returns nonzero for ci at worst.
- paulddraper 2y agoAnd then what if you combined the compiler+linter together.
- throwawaymaths 2y agoSure, as long as you don't put it in the type system.
- uecker 2y agoThis would also be my preferred solution.
- astral303 2y agoSad that C is still being utilized with a serious face. If you can't be bothered to develop in C++ and only pay for what you use, RAII is like your last problem.
- tester756 2y ago>There is no wibbly-wobbly semantics like .NET IL finalizers there is dedicated mechanism to achieve RAII-likeness in .NET: try-finally construct
- neonsunset 2y agoIt's funny this is mentioned. Misconceptions about .NET are unfortunate but unsurprising. There is no such thing as IL finalizers. There are object finalizers which are highly discouraged to be used on their own. Their most frequent application is a safety measure for objects implementing IDisposable where not calling Dispose could lead to memory leak or other form of resource starvation that must be prevented. For example, a file handle is IDisposable, so it is naturally disposed through using statement but should a user make a mistake in a scenario where that handle has non-trivial lifecycle, once the object is no longer referenced, its finalizer will be called upon one of the Gen2 GCs by a finalizer thread, preventing the file handle leakage even if its freeing is now non-deterministic: // Disposed upon exiting the scope using var okay = File.OpenHandle("file1"); // IDEs will complain if you do this, but if you insist, // the implementation will prevent you from shooting your // foot off even if it'll hurt until next Gen2 GC var leaked = File.OpenHandle("file2");