3 ms·
These are great examples. I knew that I preferred destructors over defer, but I could not explain why. You put it into words. I think people have a bias agains
by ghoward 5y ago
These are great examples. I knew that I preferred destructors over defer, but I could not explain why. You put it into words.
I think people have a bias against destructors because of C++, but they really are pretty nice. Speaking as a guy that uses C instead of C++, destructors are the one thing I would add to C.
- Arnavion 5y agoThey certainly have their problems. They're functions that get invoked without any code to explicitly invoke them. You have to consider whether a destructor can be invoked on a partially constructed object. You have to consider whether a destructor can be invoked more than once. You have to consider providing the ability to not call the destructor for performance. etc etc It's understandable why a language trying to be close to C in spirit does not have them.
- hnakamur 5y agoI agree. For example, most of Rust libraries uses the drop handler (something like desctructors) to close a file descriptor. However it has problems since in async model closing is also async and it may return an error. So in tokio-uring explicit async close will be provided. https://github.com/tokio-rs/tokio-uring/pull/1/files#diff-3dc5dd454e080eb849ee5efaf79df2585fbe0a06804d69249b4c81da05a63875R375-R400 https://github.com/tokio-rs/tokio-uring/pull/1/files#diff-3d... And you can call close like: file.close().await.unwrap(); https://github.com/tokio-rs/tokio-uring/pull/17/files#diff-bd6920ff81a489bba8cfe35dc49b5ad7bb4a4f52086f9f8766d25a8f8d791709R71 https://github.com/tokio-rs/tokio-uring/pull/17/files#diff-b...
- pcwalton 5y agoNote that there are ideas to fix this issue in the async foundations WG. It's arguably more of a problem with async as implemented in Rust than with the concept of RAII.
- ghoward 5y agoYes, those are all problems with destructors, but they are well understood. However, in a language I am currently creating, calling a destructor on a partial object is impossible because the object is created in "one" step. In other words, constructors themselves don't have access to the object in a partially created state. It does make things much easier.