HackerTrans
TopNewTrendsCommentsPastAskShowJobs

kbr-

no profile record

comments

kbr-
·tahun lalu·discuss
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.
kbr-
·tahun lalu·discuss
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).
kbr-
·tahun lalu·discuss
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.
kbr-
·tahun lalu·discuss
Yeah it's weird but the author of this post claiming that defer can replace RAII kinda suggests that. RAII isn't just about releasing the resource you acquired in the current scope in the same scope. You can pass the resource across multiple boundaries with move semantics and only at the end when it's no longer needed the resources will be released.
kbr-
·tahun lalu·discuss
> It’s a simple keyword, but it singlehandedly eliminates the need for any kind of RAII.

What if you want to put a resource object (which needs a cleanup on destruction) into a vector then give up ownership of the vector to someone?

I write code in go now after moving from C++ and God do I miss destructors. Saying that defer eliminates need for RAII triggers me so much
kbr-
·tahun lalu·discuss
Ahhahah that's beautiful, I'm crying.

Skynet sends Terminator to eradicate humanity, the Terminator uses this as its internal reasoning engine... "instructions unclear, dick caught in ceiling fan"