What should happen here?

Steven Schveighoffer schveiguy at gmail.com
Sun Sep 26 01:02:06 UTC 2021


On 9/25/21 8:23 PM, Ali Çehreli wrote:
> On 9/25/21 3:19 PM, Walter Bright wrote:
>  > On 9/25/2021 10:46 AM, Steven Schveighoffer wrote:
>  >> Right, but the optimizer is working against that.
>  >>
>  >> For example:
>  >>
>  >> ```d
>  >> auto c = new C;
>  >> .... // a whole bunch of other code
>  >>
>  >> c.method; // not necessarily still live here.
>  >> ```
>  >>
>  >> Why would it not be live there? Because the method might be inlined,
>  >> and the compiler might determine at that point that none of the data
>  >> inside the method is needed, and therefore the object is no longer
>  >> needed.
>  >>
>  >> So technically, it's not live after the original allocation. But this
>  >> is really hard for a person to determine. Imagine having the GC
>  >> collect your object when the object is clearly "used" later?
>  >
>  > I understand your point. It's value is never used again, so there is no
>  > reason for the GC to hold on to it.
> 
> I must be misunderstanding Steven's example. You say "its value is never 
> used again" yet his example has
> 
>    c.method
> 
> which to me is clearly "using" it again. So, I don't understand Steven's 
> "not necessarily still live here" comment either. Is the case today?

Yes, that is the case today.

As an example, c.method might not use any data inside c. Maybe c.method 
is `void method() {}`

But you might say "it has to pass c into it, so aha, it's live!". Except 
that it could be inlined, which effectively inlines a completely empty 
function.

But what if it's virtual? "Aha!" you might say, "now it *has* to have 
the pointer live, because it has to read the vtable". But not if your 
compiler is ldc -- it can inline virtual functions if it can figure out 
that there's no way you could have created a derived object.

As I said, the optimizer is fighting you the entire way.

Someone on Beerconf suggested destroying the object at the end of the 
struct. That actually is a reasonable solution that I don't think the 
compiler can elide. If that's what you want.

But I still am wishing for a simple "keep this alive" mechanism that 
doesn't add too much cruft, and is guaranteed to keep it alive.

-Steve


More information about the Digitalmars-d mailing list