Incorrect cast - is it the cast or the use which is undefined behavior

前端 未结 2 1705
抹茶落季
抹茶落季 2020-12-29 02:38

If I do a cast from a Base to a Derived type, but the Base type isn\'t an instance of derived type, but only use the result if it is, do I get undefined behaviour?

H

2条回答
  •  悲哀的现实
    2020-12-29 03:02

    The cast itself has undefined behaviour. Quoting C++17 (n4659) [expr.static.cast] 8.2.10/11:

    A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a class derived (Clause 13) from B, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. ... If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the behavior is undefined.

提交回复
热议问题