back

by locknitpicker·7mo ago·view on hn ↗
> Ok, but sometimes you just need a single line in a finally and writing a class is more annoying

I don't think you understand.

If you need to run cleanup code whenever you need to destroy a resource, there is already a special member function designed to handle that: the destructor. Read up on RAII.

It somehow you failed to understand RAII and basic resource management, you can still use one-liners. Read up on scope guard.

If you are too lazy to learn about RAII and too lazy to implement a basic scope guard, you can use one of the many scope guard implementations around. Even Boost has those.

https://www.boost.org/doc/libs/latest/libs/scope/doc/html/sc...

So, unless you are lazy and want to keep mindlessly writing Java in ${LANGUAGE} regardless it makes sense or not, there is absolutely no reason at all to use finally in C++.

1 comments
Slightly more than that: If you need to run cleanup code, whatever needs cleaned up should be a class and do the cleanup in the destructor.

Take a file handle, for instance. Don't use open() or fopen() and then try to close it in a finally. Instead, use a file class and let it close itself by going out of scope.