Program crash: GC destroys an object unexpectedly
Steven Schveighoffer
schveiguy at gmail.com
Thu Sep 23 18:43:36 UTC 2021
On 9/23/21 2:18 PM, eugene wrote:
> On Thursday, 23 September 2021 at 17:16:23 UTC, Steven Schveighoffer wrote:
>> 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.
>
> ```d
> void keepAlive(Object o) {
> }
>
> void main(string[] args) {
>
> import core.memory : GC;
>
> auto Main = new Main();
> Main.run();
>
> auto stopper = new Stopper();
> stopper.run();
>
> writeln(" === Hello, world! === ");
> auto md = new MessageDispatcher();
> md.loop();
>
> keepAlive(Main);
> keepAlive(stopper);
>
> writeln(" === Goodbye, world! === ");
> }
> ```
> works ok with dmd, stopper is not collected.
With dmd -O -inline, there is a chance it will be collected. Inlining is
key here.
-Steve
More information about the Digitalmars-d-learn
mailing list