Inspired by this question, I tried the following code:
struct A {
virtual void doit() const = 0;
};
struct B : public A {
virtual void doit() const;
};
struct C : public A {
virtual void doit() const;
};
void
foo(bool p)
{
const A &a = (p ? static_cast<const A &>(B()) : static_cast<const A &>(C()));
a.doit();
}
Every compiler I have tried accepts this code with -Wall -Werror
and generates the assembly I want. But after carefully reading the C++03 specification section 12.2 ("Temporaries") and section 5.12 ("Conditional Operator"), I am unsure whether this is guaranteed to work.
So, is this valid code, or does it invoke undefined behavior? Does the answer differ for C++03 and C++11?
Citations from relevant specifications would be appreciated.