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

I agree about missing RAII when switching away from C++ but it seems like defer cleans up after enclosing function exits while RAII cleans up when object goes out of scope, which is more fine-grained. Maybe I'm misunderstanding exactly when defer would clean up but it seems more like a safety feature. As people pile more stuff into the function the cleanup would be deferred more and more while RAII encapsulates the management right where you need it, e.g. exiting a loop or something.


defer-based cleanup also has the problem that, if the function plans to return a value it has to make sure to *not* defer its cleanup, and the caller then has to remember to clean it up. Destructor-based cleanup avoids these problems, but of course it's reasonable for languages (existing ones like C and even newer ones like Zig) to not want destructors, so defer is the next best thing.

Note that C++ destructors are also not ideal because they run solely based on scope. Unless RVO happens, returning a value from a function involves returning a new value (created via copy ctor or move ctor) and the dtor still runs on the value in the function scope. If the new value was created via copy ctor, that means it unnecessarily had to create a copy and then destroy the original instead of just using the original. If the new value was created via move ctor, that means the type has to be designed in such a way that a "moved-out" value is still valid to run the dtor on. It works much better in Rust where moving is not only the default but also does not leave "moved-out" husks behind, so your type does not need to encode a "moved-out" state or implement a copy ctor if it doesn't want to, and the dtor will run the fewest number of times it needs to.


This defer (using attribute cleanup) as well as Zig's are run when going out of scope. Go's runs at function exit.


Yeah, defer within scope is the most ideal form in my opinion.




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

Search: