3 ms·
> Java has scoped 'destruction' (called try-with-resources). Java's try-with-resources (and Kotlin's equivalent, .use()) are a start, but C++'s (and Rust's) ow
by cesarb 9y ago
> Java has scoped 'destruction' (called try-with-resources).
Java's try-with-resources (and Kotlin's equivalent, .use()) are a start, but C++'s (and Rust's) ownership model is stronger.
Java's model works fine when the resource doesn't have to escape the try block (and when you never forget to use the try block). But if you have a resource which might or might not escape the block (that is, its ownership might be to be passed to the caller, or to a separate long-living object), you have to do it manually, and if you're not very careful, you can have places where a stray exception leads to a resource leak. (Yes, this bit us recently at work, both the stray exception and the "another programmer didn't call .close()". Workaround for the later: finalize()...)
In "modern" C++ style (which avoids manual new/delete most of the time, instead using unique_ptr and similar), ownership transfer is easier to make reliable: you can move the ownership into the return value or into another object, without leaving any gaps where a stray exception could leak the resource. And the default is to have ownership, so less chance of leaks due to forgetting to use a try block. Rust makes it even easier to avoid such leaks (outside of reference cycles, unsafe code using raw pointers, and the "leak it on purpose" mem::forget function).