Drawbacks of exceptions being globally allocated

Tejas notrealemail at gmail.com
Mon Aug 16 06:12:14 UTC 2021


On Monday, 16 August 2021 at 05:47:10 UTC, Mathias LANG wrote:
> On Monday, 16 August 2021 at 05:36:07 UTC, Tejas wrote:
>>
>> That is why I was using heapAllocate, because using `new` on 
>> scope allocates exception on stack, and if you exit, then the 
>> exception is basically freed before it even gets caught. It 
>> fails even when you catch within the same function.
>>
>> But allocate on heap and giving ownership to a `scope` 
>> qualified variable is no problem at all. No `signal 11` 
>> killing my process ^_^
>
> You are relying on an accept-invalid though. The compiler 
> *should not* accept that code, but currently erroneously does 
> so.

okay that's it, the following is my final try for this thing:

```d
import std;
import core.lifetime:emplace;
import core.stdc.stdlib:malloc,free;

T heapAllocate(T, Args...)(Args args)@nogc{
     auto size = __traits(classInstanceSize, T);
     auto memory = malloc(size)[0 .. size];
     auto instance = emplace!(T,Args)(memory, args);
     return instance;
}

void throws()@nogc{
     auto/*no more scope*/ a = heapAllocate!(Exception)("works 
fine with scope, apparently");
     throw a;
}


void main()@nogc
{
     try{
         throws();
     } catch(Exception exp){
         scope(exit)free(cast(void*)exp);//new code
         printf("%s", cast(char*)exp.msg);
     }
}

```

There are 0 problems with this, right? I just have to remember to 
free the exception in the `catch`?


More information about the Digitalmars-d-learn mailing list