What should happen here?

Paulo Pinto pjmlp at progtools.org
Tue Sep 21 12:52:20 UTC 2021


On Tuesday, 21 September 2021 at 12:02:05 UTC, Steven 
Schveighoffer wrote:
> ...
>
> I just thought of a possible easy and effective way to ensure 
> the thing isn't collected early:
>
> ```d
> struct Pin(T)
> {
>    T t;
>    @nogc nothrow pure @safe ~this() {}
>    alias t this;
> }
>
> ...
> // usage
> auto c = Pin!C(new C); // now it needs to be held until the 
> scope ends
> ```
>
> This seems to work on LDC with -O3 to prevent the early 
> collection, so maybe it is sound? If this is a valid mechanism 
> to ensure it's saved, maybe it can be added to Phobos and the 
> spec updated to recommend that.
>
> -Steve

You just rediscovered Go's runtime.KeepAlive(), and C# 
GC.KeepAlive()

https://pkg.go.dev/runtime#KeepAlive

https://docs.microsoft.com/en-us/dotnet/api/system.gc.keepalive




More information about the Digitalmars-d mailing list