What should happen here?

Paul Backus snarwin at gmail.com
Sun Sep 26 13:29:26 UTC 2021


On Sunday, 26 September 2021 at 07:49:46 UTC, Daniel N wrote:
> // I hope this works, otherwise it violates the 'law of least 
> surprise'
> auto c = new Class()
> scope(exit) destroy(c);
>
> If scope(exit) also works, then I don't think there is any 
> problem...

Destroy on a class reference doesn't call the destructor; it just 
sets the reference to null.

If the optimizer sees that the reference isn't used again after 
that, it can remove the assignment to null as a dead store. And 
*then* if it sees that the reference isn't used after its 
initialization, it can remove the initialization as a dead store.

Basically, any clever shortcut you can come up with that "uses" 
the reference but doesn't actually do anything will fall apart as 
soon as the optimizer figures out that it doesn't actually do 
anything.

Better to use addRoot/removeRoot, which have well-defined 
semantics and will never be optimized away


More information about the Digitalmars-d mailing list