|
![](/i/fill.gif) |
Darren New <dne### [at] san rr com> wrote:
> There's really one primary problem with early returns, and that's handling
> things that ought be handled before the function returns, like deallocating
> memory, closing files, logging, etc. In a decent language like C++, there's
> invisible bits of code stuck into your object code before each return (or,
> alternately, the compiler rewrites the return statement to be a goto to the
> end of the function). Without that, it requires somewhat more code to return
> early *and* clean up, to the point where skipping over blocks with flags
> might be more clear and maintainable than duplicating clean-up code.
> Especially if you want to DRY on the cleanup code.
Maybe the fact that C++ basically removed the need for manual cleanup of
resources (if you use its constructs properly) made it much safer and
cleaner to use early returns. Early returns would indeed be a hazard in C,
where there's no automatic scope-based cleanup mechanism.
It's not just memory. It's anything that needs to be released after use,
such as for example file handles. In C++ it's completely safe to do things
like:
void foo()
{
std::ifstram is("file.txt");
do_something;
if(error) return;
do_something_else;
if(another_error) return;
do_more;
}
There's no need to clean up 'is' (ie. close the file handle) because it
will clean up itself when its scope ends. This is not possible in C (where
you always have to manually make sure it gets closed when the function is
exited).
(This is actually important because in C++ the function might be exited
at surprising places, even without explicit early returns, namely if
something throws an exception. The above code is exception-safe because
the file will be closed even if anything inside the function unexpectedly
throws.)
If you see something like this in C++:
void foo()
{
FILE* infile = std::fopen("file.txt", "r");
then you should immediately see "DANGER! DANGER!", because whatever follows
that will *not* be exception-safe (well, not unless the very next line is
'try').
--
- Warp
Post a reply to this message
|
![](/i/fill.gif) |