anonymous functions and scope(exit)

Steven Schveighoffer schveiguy at gmail.com
Sat Jul 3 17:39:18 UTC 2021


On 7/3/21 1:20 PM, Luis wrote:
> This is intentional ?
> 
> ```
>          should(function void() {
>              auto emptyStack = SimpleStack!int();
>              scope(exit) emptyStack.free; // <= This is never called
> 
>              emptyStack.reserve(16);
>              emptyStack.top;
>          }).Throw!RangeError;
> ```
> 
> scope(exit) inside of a anonymous functions, it's never called.

In principle, it should technically be called.

But in practice, the compiler does not have to clean up anything when an 
`Error` is thrown. Whether it does or not is defined by the implementation.

However, it should *always* work if it's an `Exception` and not an `Error`.

```d

import std.stdio;

void main()
{
     auto f = function void() {
         scope(exit) writeln("hi");
         throw new Exception("boo");
     };

     f();
}
```

prints "hi"

-Steve


More information about the Digitalmars-d-learn mailing list