Remix.run Logo
deagle50 4 days ago

I don't get the point, what does this have to do with defer?

kbr- 4 days ago | parent [-]

The author of the post claims that defer eliminates the need for RAII.

Well, goto also eliminates the "need" but language features are about making life easier, and life is much easier with RAII compared to having only defer.

deagle50 3 days ago | parent [-]

I got that, but the I don't see what the example of move semantics has to do with RAII or defer.

kbr- 3 days ago | parent [-]

It makes things easier. Usually the move constructor (or move assignment operator) will cause the moved-from object to stop being responsible for releasing a resource, moving the responsibility to the moved-to object. Simplest example: move- construct unique-ptr X from unique-ptr Y. When X is destroyed it will free the memory, when Y is destroyed it will do nothing.

So you can allocate resource in one function, then move the object across function boundaries, module boundaries, into another object etc. and in the end the resource will be released exactly once when the final object is destroyed. No need to remember in each of these places along the path to release the resource explicitly if there's an error (through defer or otherwise).

deagle50 3 days ago | parent [-]

I agree that it makes some things easier (at the expense of managing constructors/destructors), I'm disputing the blanket assertion that it's superior to manual management, in the context of Jai (and Odin). You're also introducing a reference count, but that's besides the point.

In Jai/Odin, every scope has default global and temp allocators, there's nothing stopping you from transferring ownership and/or passing pointers down the callstack. Then you either free in the last scope where the pointer lives or you pick a natural lifetime near the top of the callstack, defer clear temp there, and forget about it.

kbr- 2 days ago | parent | next [-]

You may also want to pass a resource through something like a channel, promise/future pair or similar. So it's not just down/up the callstack, sometimes it's "sideways". In those cases RAII is a life savior. Otherwise you have to explicitly remember about covering all possibilities: - what if resource never enters the channel - what if it enters the channel but never gets retrieved on the other side - what if the channel gets closed - what if other side tries to retrieve but cancels

Or you leak the resource.

jguegant 2 days ago | parent | prev [-]

> You're also introducing a reference count, but that's besides the point.

How so? RAII absolutely doesn't imply reference counting.