I'm wondering why simply naming an object changes its lifetime.
Foo foo(1);
// vs.
Foo(1);
I image the technical reason is that the latter is an expression instead
of a declaration. Is this correct? I would still like to learn what the
rationale is for this difference.
Why shouldn't anonymous objects live till the end of their lexical
scope? It usually doesn't make any difference, since the anonymous Foo
can't easily be referred to; but it does if the dtor has side effects.
Thanks!
-Al-
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Consider the case when Foo uses a lot of storage or critical resources
(such as file handles). Now consider what happens when you use Foo()
more than once in a lexical scope. Under present rules the compiler can
recycle the resources. In addition when ~Foo() is trivial or the
compiler can check what it is doing, the compiler may be able to
optimise away the dtor call for the first instance and just reuse that
for the second one.
> Why shouldn't anonymous objects live till the end of their lexical
> scope? It usually doesn't make any difference, since the anonymous Foo
> can't easily be referred to; but it does if the dtor has side effects.
The main reason is performance. Imagine a scenario (e.g. scientific
computing) where large temporaries are being created and piled up
until the end of scope is reached.
There are other reasons - for detailed explanation, see Chapter 6.3.2.
in The Design and Evolution of C++ (and note that Stroustrup initially
reasoned the same way as you do).
In this context, it is also worth being familiar with the latest GotW
which explains how long do the references to temporaries live:
http://herbsutter.spaces.live.com/blog/cns!2D4327CC297151BB!378.entry
Alex
> Hi.
>
> I'm wondering why simply naming an object changes its lifetime.
>
> Foo foo(1);
>
> // vs.
>
> Foo(1);
>
> I image the technical reason is that the latter is an expression instead
> of a declaration. Is this correct? I would still like to learn what the
> rationale is for this difference.
>
> Why shouldn't anonymous objects live till the end of their lexical
> scope? It usually doesn't make any difference, since the anonymous Foo
> can't easily be referred to; but it does if the dtor has side effects.
>
It seems easy to provide a name is you want it to live to the end of its
scope but how would you do the following is you rule was applied?
myFoolisness(Foo(i));// I need the destructor to be called here
The following seems pretty ugly;
{
myFoolisness(Foo(i));// I need the destructor to be called here
}
Otis