|
|
|
|
|
by foxfluff
1609 days ago
|
|
It seems a bit limiting, yes, but this does not seem like a major limitation to me. Especially if we compare it to how existing practice with goto based cleanup handlers would work in this example. It doesn't really matter that the resource was obtained in a block, the variable holding a reference is still scoped to the function body and will be checked at the end just as it would be with goto. void foo()
{
bar * b = NULL;
defer [&]{if (b) release(b);}
if (x && y)
{
this();
b = that();
}
if (something_gone_wrong())
{
return; // no problem, b gets released if it was acquired
}
...
baz(1, 2, b); // b may be null
}
If making the release conditional seems a bit hacky, remember that you need that sort of thing anyway for the hugely common case where you allocate & initialize a bunch of things and then let the caller keep the resources, except if there's an error.. in which case you need to clean everything up. Without some additional language features (first class error types or "error returns", then error defers?) these conditions are unavoidable. |
|