3 ms·
This example is exactly why RAII is the solution to this problem and not defer.
by maccard 8mo ago
This example is exactly why RAII is the solution to this problem and not defer.
- miguel_martin 8mo agodefer is literally just an explicit RAII in this example. That is, it's just unnecessary boiler plate to wrap the newResource handle into a struct in this context. In addition, RAII has it's own complexities that need to be dealt with now, i.e. move semantics, which obviously C does not have nor will it likely ever.
- maccard 8mo ago> RAII has it's own complexities that need to be dealt with now, i.e. move semantics, which obviously C does not have nor will it likely ever. In the example above, the question of "do I put defer before or after the `if err != nil` check" is deferred to the programmer. RAII forces you to handle the complexity, defer lets you shoot yourself in the foot.
- mort96 8mo agoI love RAII. C++ and Rust are my favourite languages for a lot of things thanks to RAII. RAII is not the right solution for C. I wouldn't want C to grow constructors and destructors. So far, C only runs the code you ask it to; turning variable declaration into a hidden magic constructor call would, IMO, fly in the face of why people may choose C in the first place.