Program crash: GC destroys an object unexpectedly

Steven Schveighoffer schveiguy at gmail.com
Thu Sep 23 17:16:23 UTC 2021


On 9/23/21 12:58 PM, eugene wrote:
> On Thursday, 23 September 2021 at 15:56:16 UTC, Steven Schveighoffer wrote:
>> See more details:
>>
>> https://docs.microsoft.com/en-us/dotnet/api/system.gc.keepalive?view=net-5.0#remarks 
>>
> 
> "
> This method references the obj parameter, making that object ineligible 
> for garbage collection from the start of the routine to the point, in 
> execution order, where this method is called. Code this method at the 
> end, not the beginning, of the range of instructions where obj must be 
> available.
> "
> 
> **Code this method at the end...**
> 
> :)
> it is the same as proposed by jfondren simple
> writeln(stopper.sg0.number) in the end of main, right?

Same effect, but writeln actually executes code to write data to the 
console, whereas KeepAlive doesn't do anything.

Essentially, you get the side effect of keeping the object as live, 
without paying the penalty of inserting frivolous code.

All my efforts to achieve the same via a library were thwarted by at 
least LDC (whose optimizer is very good).

The only possible solution I can think of is to generate an opaque 
function that LDC cannot see into, in order to force it to avoid 
inlining, and have that function do nothing.

However, there's always Link-Time-Optmization...

-Steve


More information about the Digitalmars-d-learn mailing list