Scope of temporaries as function arguments

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Thu Jun 27 23:15:19 PDT 2013


On Fri, 28 Jun 2013 07:11:05 +0200
"Maxim Fomin" <maxim at maxim-fomin.ru> wrote:

> On Friday, 28 June 2013 at 04:54:56 UTC, Nick Sabalausky wrote:
> > Probably a silly question, but I wanted to double-check...
> >
> > If you have this:
> >
> >     struct Foo {...}
> >     bar(Foo());
> >
> > Then regardless of optimizations (aside from any optimizer 
> > bugs, of
> > course) the Foo temporary can't go out of scope or have its 
> > dtor called
> > until bar finishes executing, right?
> 
> Struct dtor is always called in the end of the caller (bar in 
> example).
> 
> This will be OK, but in general case no. Currently object is 
> copied in caller side but destroyed in callee side, and if one of 
> the arguments next to struct is passed by invoking function which 
> throws, callee and respectively dtor will never be called.
> 

Interesting.

BTW, for anyone else reading, I just searched bugzilla and it looks
like the relevant issue is #9704.

Kinda ugly as it means refcounted RAII structs can leek under this
condition:

func(refCountedStruct, thisThrows());

Ouch.

> > Or I guess more accurately, is there any guarantee that the 
> > assert in
> > func() below should always pass?:
> >
> >     class Foo {
> >         int i = 1;
> >         //...etc...
> >     }
> >
> >     struct Bar {
> >         Foo foo;
> >         ~this() {
> >             foo.i = 2;
> >         }
> >         //...etc...
> >     }
> >
> >     void func(Bar bar)
> >     {
> >         //...anything here that *doesn't* change bar.foo.i...
> >
> >         assert(bar.foo.i == 1);  // Guaranteed to pass?
> >     }
> >
> >     void main() {
> >         Foo f = new Foo();
> >         func(Bar(f));
> >     }
> 
> Here yes, but in general case if there are other arguments, and 
> one if them passed by lambda invocation which touches f and 
> modifies, then no.

Cool, thanks.



More information about the Digitalmars-d-learn mailing list