This behavior extends to [expr.typeid] / 2 (N3936):
When typeid is applied to a glvalue expression whose type is the type of a polymorphic class, the result refers to the std::type_info object representing the type of the derived object itself (that is, the dynamic type) to which the value of glvalue refers. If the glvalue expression is obtained by applying the unary operator * to the pointer, and the pointer is the value of the null pointer, the typeid expression typeid a type exception that will correspond to the exception handler of the std::bad_typeid .
Expression 1 ? *p : *p 1 ? *p : *p always an lvalue. This is because *p is an lvalue, and [expr.cond] / 4 says that if the second and third operands for the ternary operator have the same type and category of values, then the result of the operator has this type category and values as well.
Therefore, 1 ? *m_basePtr : *m_basePtr 1 ? *m_basePtr : *m_basePtr is an lvalue of type Base . Since Base has a virtual destructor, it is a polymorphic type of class.
Therefore, this code is really an example of "When typeid is applied to a glvalue expression whose type is a polymorphic type of a class."
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 using the ternary operator. Therefore, the standard does not require an exception to be thrown if m_basePtr is null.
The behavior when m_basePtr is null will be covered by the more general null pointer dereferencing rules (which are actually a bit muddy in C ++, but for practical purposes, we assume that it causes undefined behavior here).
Finally: why would anyone write this? I think the curiousguy answer is the most plausible assumption: with this construct, the compiler does not need to insert a null pointer and code to throw an exception, so this is micro-optimization.
Presumably, the programmer is either pleased that this will never be called using a null pointer, or relies on specific processing to implement a null pointer dereferencing implementation.
MM Jan 24 '15 at 0:04 2015-01-24 00:04
source share