When are temporaries created as part of a function call destroyed?
Posted
by Michael Mrozek
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mrozek
Published on 2010-06-14T21:58:07Z
Indexed on
2010/06/14
22:02 UTC
Read the original article
Hit count: 148
Is a temporary created as part of an argument to a function call guaranteed to stay around until the called function ends, even if the temporary isn't passed directly to the function?
There's virtually no chance that was coherent, so here's an example:
class A {
public:
A(int x) : x(x) {printf("Constructed A(%d)\n", x);}
~A() {printf("Destroyed A\n");}
int x;
int* y() {return &x;}
};
void foo(int* bar) {
printf("foo(): %d\n", *bar);
}
int main(int argc, char** argv) {
foo(A(4).y());
}
If A(4)
were passed directly to foo
it would definitely not be destroyed until after the foo
call ended, but instead I'm calling a method on the temporary and losing any reference to it. I would instinctively think the temporary A
would be destroyed before foo
even starts, but testing with GCC 4.3.4 shows it isn't; the output is:
Constructed A(4)
foo(): 4
Destroyed A
The question is, is GCC's behavior guaranteed by the spec? Or is a compiler allowed to destroy the temporary A
before the call to foo
, invaliding the pointer to its member I'm using?
© Stack Overflow or respective owner