| ▲ | flakes 2 hours ago |
| I'd say a lot of users are going to borrow patterns from Go, where you'd typically check the error first. resource, err := newResource()
if err != nil {
return err
}
defer resource.Close()
IMO this pattern makes more sense, as calling exit behavior in most cases won't make sense unless you have acquired the resource in the first place.free may accept a NULL pointer, but it also doesn't need to be called with one either. |
|
| ▲ | maccard an hour ago | parent [-] |
| This example is exactly why RAII is the solution to this problem and not defer. |
| |
| ▲ | mort96 an hour ago | parent | next [-] | | I 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. | |
| ▲ | miguel_martin an hour ago | parent | prev [-] | | defer 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. |
|