Scope of temporaries as function arguments

Maxim Fomin maxim at maxim-fomin.ru
Thu Jun 27 22:11:05 PDT 2013


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.

> 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.


More information about the Digitalmars-d-learn mailing list