Store any callable in an array

wjoe none at example.com
Mon May 7 11:22:38 UTC 2018


On Monday, 7 May 2018 at 10:20:22 UTC, ag0aep6g wrote:
> On 05/07/2018 04:41 AM, wjoe wrote:
>> Could you elaborate on the unsafe destructor please?
>
> If TFunc has an unsafe destructor, asDelegate is also not safe 
> and can't be @trusted.
>
> An example of how that can break safety:
>
> ----
> auto asDelegate(TFunc)(TFunc func) @trusted
> {
>      import std.functional : toDelegate;
>      return toDelegate(func);
> }
>
> int* ptr;
> size_t length;
>
> struct S
> {
>     void opCall() {}
>     ~this() @system
>     {
>         ptr[length - 1] = 13;
>     }
> }
>
> void main() @safe
> {
>     ptr = new int;
>     length = 5; /* Whoops, got the length wrong. */
>     immutable int* imm = new int(42);
>     auto dg = asDelegate(S.init);
>     assert(*imm == 42); /* Fails. Immutability has been broken. 
> */
> }
> ----
>
> The program has undefined behavior, which means it's invalid. 
> And it's the fault of the wrong @trusted.
>
>> Are there any other gotchas ?
>
> The postblit function `this(this)` is also commonly overlooked 
> with regards to @trusted. It might not be a problem here, 
> though, because toDelegate has a `ref` parameter.
>
> An unsafe `alias this` would be another problem. Example:
> ----
> /* ... asDelegate, ptr, length, main as above ... */
> struct S
> {
>     @property T t() @system
>     {
>         ptr[length - 1] = 13;
>         return T.init;
>     }
>     alias t this;
> }
> struct T
> {
>     void opCall() {}
> }
> ----
>
> Those are the things I can see happening in asDelegate.
>
> Additionally, you'd have to check what the toDelegate call does 
> exactly before trusting it. And if it turns out that the call 
> can be trusted, then you can probably just mark toDelegate 
> itself as @trusted. And then there would be no need for 
> asDelegate anymore.

Thank you for taking the time to write up this reply and widen my 
horizon. Very much appreciated.

After further investigation I found a post where someone asked 
about the differences of function/delegate and one of the replies 
explained that functions converted to a delegate occur a 
considerable performance impact.

This and since toDelegate has a bug with @safe functions, and 
slapping a @trusted on to it sounds like more headache than it's 
worth, I will handle these cases separately.

Thanks everybody for all the replies.


More information about the Digitalmars-d-learn mailing list