Drawbacks of exceptions being globally allocated

Tejas notrealemail at gmail.com
Mon Aug 16 05:36:07 UTC 2021


On Sunday, 15 August 2021 at 20:23:03 UTC, Paul Backus wrote:
> On Sunday, 15 August 2021 at 18:47:27 UTC, Tejas wrote:
>> Do you see anything wrong with the following 
>> `emplace`-allocated, RAII following exceptions:
>>
>> [...]
>>
>> Is this good enough for general use now? Any other drawbacks?
>
> It only works if you're throwing and catching in the same 
> function. Otherwise you are essentially returning a pointer to 
> an expired stack frame, which is UB.

Guess I should've verified before accepting this as true.

```d

import std;
import core.lifetime:emplace;
import core.stdc.stdlib:malloc;

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{
     scope a = heapAllocate!(Exception)("works fine with scope, 
apparently");
     throw a;
}


void main()@nogc
{
     try{
         throws();
     } catch(Exception exp){
         printf("%s", cast(char*)exp.msg);
     }
}
```


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 
^_^


More information about the Digitalmars-d-learn mailing list