Topic: expression temporaries and conditionals
Author: algrant@myrealbox.com (Al Grant)
Date: Sat, 15 Feb 2003 00:55:27 +0000 (UTC) Raw View
What should the appended program print? Four different compilers
give four different results.
The result of the conditional expression is an rvalue, either
- an rvalue referring to the static object s
- an rvalue referring to a temporary object
Visual C++ 6.0 copy-constructs a reference-lifetime temporary
in both cases. In the 'true' case it also constructs an
expression-lifetime temporary. This would seem to correspond
to reference-binding to rvalues being implementation-defined
(as per the choice in 8.5.3#5) to use a temporary.
g++ 3.1 on the other hand constructs only a reference-lifetime
temporary. In the 'true' case this is the temporary in one
side of the conditional ("temp"); there is no copy-construction.
In the 'false' case the reference is bound to a separate object
copy-constructed from the static object. Is that allowed or
must it always make the same choice?
struct S {
S(char const *name = "def"): str(name) { printf("con %s\n", name); }
S(S const &s): str("copy") { printf("copy %s\n", s.str); }
~S() { printf("des %s\n", str); str = "*dead*"; }
void show(void) const { printf("show %s\n", str); }
char const *str;
};
S s("stat");
int f(bool n) {
printf("call %d\n", n);
S const &r = n ? S("temp") : s;
r.show();
printf("body\n");
return 0;
}
int main(int argc, char **argv) { f(true); f(false); return 0; }
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]