Does this run into undefined behavior regarding object lifetimes?
#include "stdio.h"
class C {
public:
~C() { printf("~C\n"); }
};
int I(const C& c) { printf("I\n"); return 0; }
void V(int i) { printf("V\n"); }
int main() {
V(I(C()));
return 0;
}
Seen output:
I
V
~C
what I would have开发者_如何学C expected:
I
~C
V
V(I(C()));
C()
creates a temporary which persists till the completion of the full expression, and the completion of the full expression is ;
(i.e the semicolon). That is why you see that output which is in my opinion is well-defined.
Section §12.2/3 from the Standard reads,
[...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception.
Just to emphasize, in this example the lifetime of the temporary has nothing to do with the reference or const reference parameter of function I()
. Even if the signature of I()
is:
int I(C c); //instead of : int I(const C & c);
the temporary would persist till the completion of the full expression and you would see exactly the same output.
See this: http://www.ideone.com/RYWhy
The call to V
returns before the full expression has been completely evaluated. And when V
has returned, it will have printed its stuff (there is a sequence point before returning from V
).
The temporary C()
is only destroyed after the complete full expression has been evaluated.
Why? The temporary lives till the end of the full expression.
The behavior you are seeing is the one mandated by the standard: temporaries are destroyed at the end of the full expression creating them.
Historically another behavior was seen (and is still available in some compilers): destruction at the end of the block. In your case it wouldn't have made a difference as it delays still further the destruction.
精彩评论