Re: cleanup of temporary objects
On Feb 29, 11:58 am, yev...@gmail.com wrote:
Consider the following code:
class A {
int x;
public:
A() { printf("In A()\n"); x = 5; }
~A() { printf("In ~A()\n"); }
operator int *() { printf("In int *()\n"); return &x; }
};
A f1()
{
printf("in f1()\n");
return A();
}
void foo(int *p) { printf("in foo()\n"); }
int main()
{
foo(f1());
printf("After foo()\n");
return 0;
}
I have always thought this code is wrong because the temporary
object A would be destroyed after calling int *() operator and
before entering foo(), so the pointer p would point to freed
memory. However i complied the code in both vs2005 and gcc
compilers and ran it, it complies fine and the result in both
cases is the following:
in f1()
In A()
In int *()
in foo()
In ~A()
After foo()
That means that temporary A is kept alive for the duration of
function foo(). So what should be correct behaviour according
to c++ standard regarding when the temporary is freed? Is the
code above portable?
According to the standard, the lifetime of a temporary is until
the end of the full expression in which it was created. There
are a few special cases where the lifetime may be extended, but
it is never shorter. And unless you are in one of the special
cases where it is extended, it may not be longer.
Note that this wasn't always the case. When I was learning C++,
it was more or less unspecified, and could be anywhere between
the "use" of the temporary (here, the call of the function
operator int*()) and the end of the block. The literature at
the time warned of this potential problem---perhaps you have
been reading something out of data. (FWIW: of the two compilers
I used at the time, CFront destructed at the end of the block,
and g++ after first use. Even today, by default, Sun CC defers
destruction till the end of the block, in order to avoid
breaking code written for CFront which depended on this.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]