Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

defer-based cleanup also has the problem that, if the function plans to return a value it has to make sure to *not* defer its cleanup, and the caller then has to remember to clean it up. Destructor-based cleanup avoids these problems, but of course it's reasonable for languages (existing ones like C and even newer ones like Zig) to not want destructors, so defer is the next best thing.

Note that C++ destructors are also not ideal because they run solely based on scope. Unless RVO happens, returning a value from a function involves returning a new value (created via copy ctor or move ctor) and the dtor still runs on the value in the function scope. If the new value was created via copy ctor, that means it unnecessarily had to create a copy and then destroy the original instead of just using the original. If the new value was created via move ctor, that means the type has to be designed in such a way that a "moved-out" value is still valid to run the dtor on. It works much better in Rust where moving is not only the default but also does not leave "moved-out" husks behind, so your type does not need to encode a "moved-out" state or implement a copy ctor if it doesn't want to, and the dtor will run the fewest number of times it needs to.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: