This behaviour is covered by [expr.typeid]/2 (N3936):
When typeid
is applied to a glvalue expression whose type is a polymorphic class type, the result refers to a std::type_info
object representing the type of the most derived object (that is, the dynamic type) to which the glvalue refers. If the glvalue expression is obtained by applying the unary *
operator to a pointer and the pointer is a null pointer value, the typeid
expression throws an exception of a type that would match a handler of type std::bad_typeid
exception.
The expression 1 ? *p : *p
is always an lvalue. This is because *p
is an lvalue, and [expr.cond]/4 says that if the second and third operand to the ternary operator have the same type and value category, then the result of the operator has that type and value category also.
Therefore, 1 ? *m_basePtr : *m_basePtr
is an lvalue with type Base
. Since Base
has a virtual destructor, it is a polymorphic class type.
Therefore, this code is indeed an example of "When typeid
is applied to a glvalue expression whose type is a polymorphic class type" .
Now we can read the rest of the above quote. The glvalue expression was not "obtained by applying the unary *
operator to a pointer" - it was obtained via the ternary operator. Therefore the standard does not require that an exception be thrown if m_basePtr
is null.
The behaviour in the case that m_basePtr
is null would be covered by the more general rules about dereferencing a null pointer (which are a bit murky in C++ actually but for practical purposes we'll assume that it causes undefined behaviour here).
Finally: why would someone write this? I think curiousguy's answer is the most plausible suggestion so far: with this construct, the compiler does not have to insert a null pointer test and code to generate an exception, so it is a micro-optimization.
Presumably the programmer is either happy enough that this will never be called with a null pointer, or happy to rely on a particular implementation's handling of null pointer dereference.
1 ? ...
) – Hygienicstypeid(*m_basePtr ? *m_basePtr : *m_basePtr)
. – Flyerm_basePtr
points to an object that is derived fromDerived
(unless they really wanted to returntrue
only if the object was precisely of typeDerived
). And that's not even considering ifm_basePtr
points to another kind of type that's derived fromBase
but isn't in theDerived
hierarchy. But I could envision that being intended even it it's probably a problematic design. – DumahBase
would need to be convertible tobool
. Not true in the real project's code. – Sabin